Consider the following:
var params = location.search.match(/=([\w\d-]+)&?/g);
console.log(params);
The output is:
["=7&", "=31500&", "=1"]
I don't wont any signs there, digits or words only, so I've set parentheses, but it doesn't work. So how do I do it?
Consider the following:
var params = location.search.match(/=([\w\d-]+)&?/g);
console.log(params);
The output is:
["=7&", "=31500&", "=1"]
I don't wont any signs there, digits or words only, so I've set parentheses, but it doesn't work. So how do I do it?
Share Improve this question edited Jul 6, 2013 at 21:30 Ashwini Chaudhary 251k60 gold badges475 silver badges515 bronze badges asked May 25, 2011 at 7:58 nonamenoname 55110 silver badges29 bronze badges 2- 1 could you also provide the input that you're using? – Russ Cam Commented May 25, 2011 at 8:01
- @Russ: I'd say it's something along the lines of "?foo=7&bar=31500&baz=1". It's not that hard to deduce.. ;-) – Martijn Pieters Commented May 25, 2011 at 8:37
3 Answers
Reset to default 2Are you getting the querystring parameter? I think this is what you want (although it doesn't use regular expression).
<script type="text/javascript">
<!--
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
var koko = querySt("koko");
document.write(koko);
document.write("<br>");
document.write(hu);
-->
</script>
Reference: http://ilovethecode./Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml
There's a nice javascript function called gup() which makes this sort of thing simple. Here's the function:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
and sample usage:
var myVar = gup('myVar');
So, if your querystring looks like this: ?myVar=asdf
myVar will return 'asdf'.
The .match
method returns the whole matched string, not any groupings you have defined with parenthesis.
If you want to return just a grouping in a regular expression, you'll have to use the .exec
method multiple times, and extract the matched group from the resulting array:
var search = location.search,
param = /=([\w\d-]+)&?/g,
params = [],
match;
while ((match = param.exec(search)) != null) {
params.push(match[1]);
}
console.log(params);
This works because the g
flag is used on the regular expression. Every time you call .exec
on the param
regular expression, it's lastIndex
attribute is set to the next matching substring and that in turn makes sure that the next call to .exec
starts searching at the next match. The resulting array contains the whole matched string at index 0, then every matched group at subsequent positions. Your group is thus returned as index 1 of the array.