noname
noname

Reputation: 551

JavaScript regular expression match

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?

Upvotes: 3

Views: 4887

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121256

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.

Upvotes: 2

Billy
Billy

Reputation: 15706

Are 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.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml

Upvotes: 2

squidbe
squidbe

Reputation: 1021

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'.

Upvotes: 2

Related Questions