Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get query string values using non-capturing group

Given this query string:

?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0

How can I extract the values from only these param types 'product_cat, product_tag, attr_color, attr_size' returning only 'mens-jeans,shirts,fall,classic-style,charcoal,brown,large,x-small?

I tried using a non-capturing group for the param types and capturing group for just the values, but its returning both.

(?:product_cats=|product_tags=|attr\w+=)(\w|,|-)+
like image 447
Benjamin Avatar asked Sep 28 '22 18:09

Benjamin


3 Answers

You can collect tha values using

(?:product_cats|product_tags|attr\w+)=([\w,-]+)

Mind that a character class ([\w,-]+) is much more efficient than a list of alternatives ((\w|,|-)*), and we avoid the issue of capturing just the last single character.

Here is a code sample:

var re = /(?:product_cats|product_tags|attr\w+)=([\w,-]+)/g; 
var str = '?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0';
var res = [];
while ((m = re.exec(str)) !== null) {
    res.push(m[1]);
}
document.getElementById("res").innerHTML = res.join(",");
<div id="res"/>
like image 61
Wiktor Stribiżew Avatar answered Oct 19 '22 00:10

Wiktor Stribiżew


You can always use a jQuery method param.

like image 45
stile17 Avatar answered Oct 18 '22 23:10

stile17


You can use following simple regex :

/&\w+=([\w,-]+)/g

Demo

You need to return the result of capture group and split them with ,.

var mystr="?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0
";
var myStringArray = mystr.match(/&\w+=([\w,-]+)/g);
var arrayLength = myStringArray.length-1; //-1 is because of that the last match is 0
var indices = [];
for (var i = 0; i < arrayLength; i++) {
    indices.push(myStringArray[i].split(','));
}
like image 1
Mazdak Avatar answered Oct 18 '22 23:10

Mazdak