I'm trying to do a URL GET variable replace, however the regular expression for checking whether the variable exists in amongst other GET variables is returning true when I am expecting it to return false.
The pattern I am using is: &sort=.*&
Test URL: http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Full code:
var sort = getOptionValue($(this).attr('id'));
var url = document.URL;
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
if(url.search('/&sort=.*&/i')) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i')) {
url.replace('/&sort=.*/i','&sort='+sort);
}
}
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Well, you are using String.search, which, according to the linked documentation:
If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.
So it will return -1, or 0 or greater when there is a match. So you should test for -1, not truthiness.
Also, there is no need to pass the regexes as strings, you might as well use:
url.replace(/&sort=.*&/i,'&sort='+sort+'&');
Further, keep in mind that replace will create a new string, not replace in the string (strings in Javascript are immutable).
Finally, I don't see the need for searching for the string, and then replacing it -- it seems that you always want to replace &sort=SOMETHING with &sort=SOMETHING_ELSE, so just do that:
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
url = url.replace(/&sort=[^&]*/i, '&sort=' + sort);
}
The javascript string function search() returns -1 if not found, not false. Your code should read:
if(url.search('/&sort=.*&/i') != -1) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i') != -1) {
url.replace('/&sort=.*/i','&sort='+sort);
}
You should check
if(url.search('/&sort=.*&/i') >= 0)
then it should work
You could use this code
var url = 'http://localhost/search?location=any&sort=asc';
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
console.log(vars);
//vars is an object with two properties: location and sort
This can be done by using
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + sort);
The match broken down
Group 1 matches for ? or &
Group 2 matches sort=
Group 3 matches anything that is not a & or ?
Then "$1$2" + sort will replace all 3 group matches with the first 2 + your variable
examples using string "REPLACE" instead of your sort variable
url = "http://localhost/search?location=any&sort=asc&a=z"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE&a=z"
url = "http://localhost/search?location=any&sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE"
url = "http://localhost/search?sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE"
url = "http://localhost/search?sort=asc&z=y"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE&z=y"
The pattern I am using is: &sort=.*& Test URL:
http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on
the basis that their is no ampersand character following the sort
parameter's value?
you are assuming right. But in your code you have else if(url.search('/&sort=.*/i')) which will match and thus still replace the value.
You should also note that your code would turn http://localhost/search?sort=asc&location=any&some=more into http://localhost/search?sort=asc&some=more. that's because because .* is greedy (trying to match as much as possible). You can avoid that by telling it to match as little as possible by appending a ? like so .*?.
That said, I believe you may be better off with a library that knows how URLs actually work. You're not compensating for parameter position, possible escaped values etc. I suggest you have a look at URI.js and replace your wicked regex with
var uri = URI(document.URL),
data = uri.query(true);
data.foo = 'bazbaz';
uri.query(data);
Related
Is there a way to obtain a URL parameter in a case insensitive way using jquery?
Essentially, I'm looking to do something like $.url('?someparameter');, where it would match both http:\\www.test.com?someparameter=ABC or
http:\\www.test.com?SOMEparAMeter=ABC
You should try toLowerCase. This function converts any string to lowercase.
Use a regular expression where you set the case-insensitive flag.
Regular Expressions -- scroll down to "Advanced Searching With Flags"
Please take a look at: How can I get query string values in JavaScript?
The line to adapt to your needs is as follows:
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)", "i");
//"i" for case-insensitive
This doesnt use jQuery, just javascript. But it addresses the question in general.
The problem w/ ucasing the entire ULR is you may be keying off the value to look up an HTML element.
why there is not a collection of keys in URL.searchParams, I do not know, but there is not.
Below is a function i wrote that will find a key and return a value.
I am just barely literate in regEx, so I am sure there is a better regEx that can pull the
value out and omit trailing key value pairs.
function getParm_CI(parm) {
var str = window.location.href;
var rgx = new RegExp('\\b' + parm + '=.*\\b', 'gi');
//this gets an array of matches
var aMatches = str.match(rgx);
if (aMatches == null) return;
var parmVal = aMatches[0].substring(parm.length + 1);
//we shouldnt, but make sure there are not trailing parms
var idx = parmVal.indexOf('&');
//alert('amp:' + idx);
if (idx > -1) parmVal = parmVal.substring(0, idx);
return parmVal;
}
usage would be like this
var topic = getParm_CI('SOMEparAMeter');
I need to write a function to perform an action only if the URL has a specific string. The issue that I am finding is that the string can come up in multiple instances as part of another string. I need the function to run when the string is ONLY "?page=1". What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. How do I do that? I've tried a couple of different ways, but it does not work. Any help is appreciated. Here is the latest code that I have used that is close...but no cigar.
var location = window.location.href;
if (location.indexOf("?page=1") > -1){
//Do something
};
?page is a GET parameter. It doesn't necessarily have to be first in the URL string. I suggest you properly decode the GET params and then base your logic on that. Here's how you can do that:
function unparam(qs) {
var params = {},
e,
a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(qs)) {
params[d(e[1])] = d(e[2]);
}
return params;
}
var urlParams = unparam(window.location.search.substring(1));
if(urlParams['page'] == '1') {
// code here
}
Alternatively, a regex with word boundaries would have worked:
if(/\bpage=1\b/.test(window.location.search)) {
// code here
}
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {
}
You could look at the character immediately following the string "?page=1" in the url. If it's a digit,you don't have a match otherwise you do. You could trivially do something like this:
var index = location.indexOf("?page=1"); //Returns the index of the string
var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
//Unicode values for 0-9 is 48-57, check if number lies within this range
Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. I hope this points you in the right direction.
Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions
The replace function returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned. Is there a way to know whether it actually replaced anything apart from comparing the result with the original string?
A simple option is to check for matches before you replace:
var regex = /i/g;
var newStr = str;
var replaced = str.search(regex) >= 0;
if(replaced){
newStr = newStr.replace(regex, '!');
}
If you don't want that either, you can abuse the replace callback to achieve that in a single pass:
var replaced = false;
var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});
As a workaround you can implement your own callback function that will set a flag and do the replacement. The replacement argument of replace can accept functions.
Comparing the before and after strings is the easiest way to check if it did anything, there's no intrinsic support in String.replace().
[contrived example of how '==' might fail deleted because it was wrong]
Javascript replace is defected by design. Why? It has no compatibility with string replacement in callback.
For example:
"ab".replace(/(a)(b)/, "$1$2")
> "ab"
We want to verify that replace is done in single pass. I was imagine something like:
"ab".replace(/(a)(b)/, "$1$2", function replacing() { console.log('ok'); })
> "ab"
Real variant:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
return "$1$2";
})
> ok
> "$1$2"
But function replacing is designed to receive $0, $1, $2, offset, string and we have to fight with replacement "$1$2". The solution is:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
// arguments are $0, $1, ..., offset, string
return Array.from(arguments).slice(1, -2)
.reduce(function (pattern, match, index) {
// '$1' from strings like '$11 $12' shouldn't be replaced.
return pattern.replace(
new RegExp("\\$" + (index + 1) + "(?=[^\\d]|$)", "g"),
match
);
}, "$1$2");
});
> ok
> "ab"
This solution is not perfect. String replacement itself has its own WATs. For example:
"a".replace(/(a)/, "$01")
> "a"
"a".replace(/(a)/, "$001")
> "$001"
If you want to care about compatibility you have to read spec and implement all its craziness.
If your replace has a different length from the searched text, you can check the length of the string before and after. I know, this is a partial response, valid only on a subset of the problem.
OR
You can do a search. If the search is successfull you do a replace on the substring starting with the found index and then recompose the string. This could be slower because you are generating 3 strings instead of 2.
var test = "Hellllo";
var index = test.search(/ll/);
if (index >= 0) {
test = test.substr(0, index - 1) + test.substr(index).replace(/ll/g, "tt");
}
alert(test);
While this will require multiple operations, using .test() may suffice:
const regex = /foo/;
const yourString = 'foo bar';
if (regex.test(yourString)) {
console.log('yourString contains regex');
// Go ahead and do whatever else you'd like.
}
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.
With indexOf you can check wether a string contains another string.
Seems like you might want to use that.
have a look at string.match() or string.search()
After doing any RegExp method, read RegExp.lastMatch property:
/^$/.test(''); //Clear RegExp.lastMatch first, Its value will be ''
'abcd'.replace(/bc/,'12');
if(RegExp.lastMatch !== '')
console.log('has been replaced');
else
console.log('not replaced');
Here is an example of the url i'm trying to match: http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx
What im trying to match is http: //store.mywebsite.com/folder-1 except that "folder-1" will always be a different value. I can't figure out how to write an if statement for this:
Example (pseudo-code)
if(url contains http://store.mywebsite.com/folder-1)
do this
else if (url contains http://store.mywebsite.com/folder-2)
do something else
etc
In the interest of keeping things very simple...
if(location.pathname.indexOf("folder-1") != -1)
{
//do things for "folder-1"
}
this might give you false positives if the value "folder-1" could be present in other parts of the string. If you are already making sure this is not the case, the provided example should be sufficient.
I would split() the string and check an individual component of the url:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
// split the string into an array of parts
var spl = str.split("/");
// spl is now [ http:,,store.mywebsite.com,folder-1,folder-2,item3423434.aspx ]
if (spl[4] == "folder-1") {
// do something
} else if (spl[4] == "folder-2") {
// do something else
}
Using this method it's easy to check other parts of the URL too, without having to use a regular expression with sub-expression captures. e.g. matching the second directory in the path would be if spl[5] == "folder-x".
Of course, you could also use indexOf(), which will return the position of a substring match within a string, but this method is not quite as dynamic and it's not very efficient/easy to read if there are going to be a lot of else conditions:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
if (str.indexOf("http://store.mywebsite.com/folder-1") === 0) {
// do something
} else if (str.indexOf("http://store.mywebsite.com/folder-2") === 0) {
// do something
}
Assuming the base URL is fixed and the folder numbers can be very large then this code should work:
var url = 'http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx'
, regex = /^http:..store.mywebsite.com.(folder-\d+)/
, match = url.match(regex);
if (match) {
if (match[1] == 'folder-1') {
// Do this
} else if (match[1] == 'folder-2') {
// Do something else
}
}
Just use URL parting in JS and then you can match URL's against simple string conditions or against regular expressions