1

I need to parse url in JavaScript.

Here is my code:

var myRe = /\?*([^=]*)=([^&]*)/;
var myArray = myRe.exec("?page=3&Name=Alex");
for(var i=1;i<myArray.length;i++)
{
 alert(myArray[i]); 
}

Unfortunately it only works for first name=value pair.

How I can correct my code?

pimvdb
155k80 gold badges312 silver badges357 bronze badges
asked Sep 2, 2011 at 13:12
2
  • possible duplicate of Parse query string in JavaScript Commented Sep 2, 2011 at 13:15
  • According to your example You need to parse only Query String part of URL (after question sign)? Commented Sep 2, 2011 at 13:17

3 Answers 3

4

exec returns a match, or null if no match found. So you need to keep execing until it returns null.

var myRe = /\?*([^=]*)=([^&]*)/;
var myArray;
while((myArray = myRe.exec("?page=3&Name=Alex")) !== null)
{
 for(var i=1;i<myArray.length;i++)
 {
 alert(myArray[i]); 
 }
}

Also, you're regex is wrong, it definately needs th g switch, but I got it working using this regex:

var regex = /([^=&?]+)=([^&]+)/g;

See Live example: http://jsfiddle.net/GyXHA/

answered Sep 2, 2011 at 13:15
Sign up to request clarification or add additional context in comments.

3 Comments

+1 exec will return an array or null, so !== null is superfluous. Also, you might want to add a semicolon on the second line.
this dont works for "?page=&Name=Alex" (page parameter has empty value) and, possible, if anchor id # is specified
@Andrew - was there a requirement for it to do so? Plus change the *'s for + and it'll work for blank values too.
0

If all you're trying to do is get query string name/value pairs you could do something like this:

function getQueryStringValue(varName) {
 var query = window.location.search.substring(1);
 var vars = query.split("&");
 for (var i = 0; i < vars.length; i++) {
 var pair = vars[i].split("=");
 if (pair[0] == varName) { return pair[1]; }
 }
}
answered Sep 2, 2011 at 13:20

Comments

0
var qs="da?page=3&page=4&Name=&xxx=43&page=&#adasdsadsa";
var params=qs.replace(/^.*\??/g,'').replace(/#.*/g,'').match(/[^&\?]+/g);
var args={};
if(params)for(var i=0;i<params.length;i++) {
 var propval=params[i].split('=');
 if(!args.hasOwnProperty(propval[0]))args[propval[0]]=[];
 args[propval[0]].push(propval[1]);
}
// result:
// args=== {
// Name: [""],
// page: ["3","4",""],
// xxx: ["43"]
// }
answered Sep 2, 2011 at 14:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.