4

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?

0

2 Answers 2

4

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);
}

Sign up to request clarification or add additional context in comments.

Comments

1

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
    }
}

Comments

Your Answer

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.