Reputation: 71
this is actually the first time I encounter this problem. I'am trying to parse a string for key value pairs where the seperator can be a different character. It works fine at any regex tester but not in my current JS project. I already found out, that JS regex works different then for example php. But I couldn't find what to change with mine.
My regex is the following:
[(\?|\&|\#|\;)]([^=]+)\=([^\&\#\;]+)
it should match:
#foo=bar#site=test
MATCH 1
1. [1-4] `foo`
2. [5-8] `bar`
MATCH 2
1. [9-13] `site`
2. [14-18] `test`
and the JS is:
'#foo=bar#site=test'.match(/[(\?|\&|\#|\;)]([^=]+)\=([^\&\#\;]+)/g);
Result:
["#foo=bar", "#site=test"]
For me it looks like the grouping is not working properly. Is there a way around this?
Upvotes: 4
Views: 1105
Reputation: 5705
I wouldn't rely on a complex regex which could fail anytime for strange reasons and is hard to read but use simple functions to split the string:
var str = '#foo=bar#site=test'
// split it by # and do a loop
str.split('#').forEach(function(splitted){
// split by =
var splitted2 = splitted.split('=');
if(splitted2.length === 2) {
// here you have
// splitted2[0] = foo
// splitted2[1] = bar
// and in the next iteration
// splitted2[0] = site
// splitted2[1] = test
}
}
Upvotes: 1
Reputation: 1074188
String#match
doesn't include capture groups. Instead, you loop through regex.exec
:
var match;
while (match = regex.exec(str)) {
// Use each result
}
If (like me) that assignment in the condition bothers you, you can use a !!
to make it clearly a test:
var match;
while (!!(match = regex.exec(str))) {
// Use each result
}
Example:
var regex = /[(\?|\&|\#|\;)]([^=]+)\=([^\&\#\;]+)/g;
var str = '#foo=bar#site=test';
var match;
while (!!(match = regex.exec(str))) {
console.log("result", match);
}
Upvotes: 4