Javascript get query string values using non-capturing group - javascript

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|,|-)+

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"/>

You can always use a jQuery method param.

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(','));
}

Something like
/(?:product_cats|product_tag|attr_color|attr_size)=[^,]+/g
(?:product_cats|product_tag|attr_color|attr_size) will match product_cats or product_tag or attr_color or attr_size)
= Matches an equals
[^,] Negated character class matches anything other than a ,. Basically it matches till the next ,
Regex Demo
Test
string = "?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0";
matched = string.match(/(product_cats|product_tag|attr_color|attr_size)=[^,]+/g);
for (i in matched)
{
console.log(matched[i].split("=")[1]);
}
will produce output as
mens-jeans
charcoal
large

There is no need for regular expressions. just use splits and joins.
var s = '?cgan=1&product_cats=mens-jeans,shirts&product_tags=fall,classic-style&attr_color=charcoal,brown&attr_size=large,x-small&cnep=0';
var query = s.split('?')[1],
pairs = query.split('&'),
allowed = ['product_cats', 'product_tags', 'attr_color', 'attr_size'],
results = [];
$.each(pairs, function(i, pair) {
var key_value = pair.split('='),
key = key_value[0],
value = key_value[1];
if (allowed.indexOf(key) > -1) {
results.push(value);
}
});
console.log(results.join(','));
($.each is from jQuery, but can easily be replaced if jQuery is not around)

Related

Javascript regex capture giving unexpected results

I am trying to capture all data before the first _. What I have so far is
const regex = /(.*)(?=_)/g;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
The output is an array Array ["Mike_Jones","" ]
What I was expecting was Mike
Use /^[^_]*/
^ looks from the beginning of the string
[^_] negates the _
* gives any number of characters
const regex = /^[^_]*/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
var s = "Mike_Jones_Jr";
console.log(s.split('_')[0]);
Create a capture group ((something between parentheses)) that starts at the beginning of the line (^) and is lazy (.*?), then grab the second item in the matching array.
const regex = /(^.*?)_/s
console.log('Mike_Jones_Jr'.match(regex)[1] || '')
console.log(`Mike
_Jones_Jr`.match(regex)[1] || '')
You can simply use split,
Note:- Second parameter is to limit the number of elements in final outptut
var s = "Mike_Jones_Jr";
console.log( s.split('_', 1) );
If you want to do using regex, you can drop the g flag
const regex = /^[^_]*(?=_)/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
console.log("_ melpomene is awesome".match(regex));

How to find special characters in a string and store in an array in javascript

Example of a string
"/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>"
characters occurs like A, B, C and .... are variables and count is not fixed
How to identifies how many variables are there and stored in an array
Use regex to find all your matches.
Using a while loop you can iterate through multiple matches and push them in an array. Try this.
var String = "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>";
var myRegexp = /\<.\>/gm;
var matches = [];
var match = myRegexp.exec(String);
while (match != null) {
matches.push(match[0])
match = myRegexp.exec(String);
}
console.log(matches)
Please review below code that will help to resolve your issue. It may find any non word characters and create a non-word array.
let str = "/city=<A>/state=<B>/sub_div=<C>/type=pos/div=<D>/cli_name=Cstate<E>/<F>/<G>";
let arrStr = str.split("");
var strRegExp = /\W/g;
let arrNonWord = [];
arrStr.forEach(function(str){
var result = str.match(strRegExp);
if(result)
arrNonWord.push(result[0]);
});
console.log(arrNonWord);

JavaScript RegExp - find all prefixes up to a certain character

I have a string which is composed of terms separated by slashes ('/'), for example:
ab/c/def
I want to find all the prefixes of this string up to an occurrence of a slash or end of string, i.e. for the above example I expect to get:
ab
ab/c
ab/c/def
I've tried a regex like this: /^(.*)[\/$]/, but it returns a single match - ab/c/ with the parenthesized result ab/c, accordingly.
EDIT :
I know this can be done quite easily using split, I am looking specifically for a solution using RegExp.
NO, you can't do that with a pure regex.
Why? Because you need substrings starting at one and the same location in the string, while regex matches non-overlapping chunks of text and then advances its index to search for another match.
OK, what about capturing groups? They are only helpful if you know how many /-separated chunks you have in the input string. You could then use
var s = 'ab/c/def'; // There are exact 3 parts
console.log(/^(([^\/]+)\/[^\/]+)\/[^\/]+$/.exec(s));
// => [ "ab/c/def", "ab/c", "ab" ]
However, it is unlikely you know that many details about your input string.
You may use the following code rather than a regex:
var s = 'ab/c/def';
var chunks = s.split('/');
var res = [];
for(var i=0;i<chunks.length;i++) {
res.length > 0 ? res.push(chunks.slice(0,i).join('/')+'/'+chunks[i]) : res.push(chunks[i]);
}
console.log(res);
First, you can split the string with /. Then, iterate through the elements and build the res array.
I do not think a regular expression is what you are after. A simple split and loop over the array can give you the result.
var str = "ab/c/def";
var result = str.split("/").reduce(function(a,s,i){
var last = a[i-1] ? a[i-1] + "/" : "";
a.push(last + s);
return a;
}, []);
console.log(result);
or another way
var str = "ab/c/def",
result = [],
parts=str.split("/");
while(parts.length){
console.log(parts);
result.unshift(parts.join("/"));
parts.pop();
}
console.log(result);
Plenty of other ways to do it.
You can't do it with a RegEx in javascript but you can split parts and join them respectively together:
var array = "ab/c/def".split('/'), newArray = [], key = 0;
while (value = array[key++]) {
newArray.push(key == 1 ? value : newArray[newArray.length - 1] + "/" + value)
}
console.log(newArray);
May be like this
var str = "ab/c/def",
result = str.match(/.+?(?=\/|$)/g)
.map((e,i,a) => a[i-1] ? a[i] = a[i-1] + e : e);
console.log(result);
Couldn't you just split the string on the separator character?
var result = 'ab/c/def'.split(/\//g);

Display characters other than alphabets using reqular expression

I have tried to display characters other than alphabets in the particular string but it is displaying only the first char.
var myArray = /[^a-zA-Z]+/g.exec("cdAbb#2547dbsbz78678");
The reason it is only displaying the first character is because with using exec and the g modifier (global), this method is meant to be used in a loop for getting all sub matches.
var str = "cdAbb#2547dbsbz78678";
var re = /[^a-zA-Z]+/g;
var myArray;
while (myArray = re.exec(str)) {
console.log(myArray[0]);
}
Output
#2547
78678
If you were wanting to combine the matches you could use the following.
var str = "cdAbb#2547dbsbz78678",
res = str.match(/[\W\d]+/g).join('');
# => "#254778678"
Or do a replacement
str = str.replace(/[a-z]+/gi, '');
You can do:
"cdAbb#2547dbsbz78678".match(/[^a-zA-Z]+/g).join('');
//=> #254778678
RegExp.exec with g (global) modifier needs to run in loop to give you all the matches.

Using Regex to pull out a part of a string

I can't figure out how to pull out multiple matches from the following example:
This code:
/prefix-(\w+)/g.exec('prefix-firstname prefix-lastname');
returns:
["prefix-firstname", "firstname"]
How do I get it to return:
[
["prefix-firstname", "firstname"],
["prefix-lastname", "lastname"]
]
Or
["prefix-firstname", "firstname", "prefix-lastname", "lastname"]
This will do what you want:
var str="prefix-firstname prefix-lastname";
var out =[];
str.replace(/prefix-(\w+)/g,function(match, Group) {
var row = [match, Group]
out.push(row);
});
Probably a mis-use of .replace, but I don't think you can pass a function to .match...
_Pez
Using a loop:
re = /prefix-(\w+)/g;
str = 'prefix-firstname prefix-lastname';
match = re.exec(str);
while (match != null) {
match = re.exec(str);
}
You get each match one at a time.
Using match:
Here, the regex will have to be a bit different, because you cannot get sub-captures (or I don't know how to do it with multiple matches)...
re = /[^\s-]+(?=\s|$)/g;
str = 'prefix-firstname prefix-lastname';
match = str.match(re);
alert(match);
[^\s-]+ matches all characters except spaces and dashes/hyphens only if they are followed by a space or are at the end of the string, which is a confition imposed by (?=\s|$).
You can find the groups in two steps:
"prefix-firstname prefix-lastname".match(/prefix-\w+/g)
.map(function(s) { return s.match(/prefix-(\w+)/) })

Categories

Resources