I need to match an expression and extract values from it using named groups.
Lets say this is my string:
JavaScript
x
2
1
var str = 'element=123'
2
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:
JavaScript
1
2
1
new RegExp(/^(<element>[A-Za-z0-9])+=[A-Za-z0-9]+$/);
2
What am I doing wrong?
Advertisement
Answer
JavaScript does not support named capture groups.
You will have to use numbered groups.
For instance:
JavaScript
1
8
1
var myregex = /([^=]+)=(.*)/;
2
var matchArray = myregex.exec(yourString);
3
if (matchArray != null) {
4
element = matchArray[1];
5
id = matchArray[2];
6
7
}
8
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.