Skip to content
Advertisement

Javascript: Named Capture Groups

I need to match an expression and extract values from it using named groups.

Lets say this is my string:

var str = 'element=123'

So i want to match it using regex and extract the element and value.

I know how to do it is c#, I am trying to figure it out in JS.

This is my regex:

new RegExp(/^(<element>[A-Za-z0-9])+=[A-Za-z0-9]+$/);

What am I doing wrong?

Advertisement

Answer

JavaScript does not support named capture groups.

You will have to use numbered groups.

For instance:

var myregex = /([^=]+)=(.*)/;
var matchArray = myregex.exec(yourString);
if (matchArray != null) {
    element = matchArray[1];
    id = matchArray[2];

} 

Option 2: XRegExp

The alternate regex library for JavaScript XregexP supports named captures as well as other important regex features missing from JS regex, such as lookbehinds.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement