Saturday, 23 April 2016

regex - Javascript Regular Expression multiple match




I'm trying to use javascript to do a regular expression on a url (window.location.href) that has query string parameters and cannot figure out how to do it. In my case, there is a query string parameter can repeat itself; for example "quality", so here I'm trying to match "quality=" to get an array with the 4 values (tall, dark, green eyes, handsome):



http://www.acme.com/default.html?id=27&quality=tall&quality=dark&quality=green eyes&quality=handsome

Answer



You can use a regex to do this.



var qualityRegex = /(?:^|[&;])quality=([^&;]+)/g,
matches,

qualities = [];

while (matches = qualityRegex.exec(window.location.search)) {
qualities.push(decodeURIComponent(matches[1]));
}


jsFiddle.



The qualities will be in qualities.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...