13

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?

2
  • 2
    stackoverflow.com/questions/5367369/…
    – trainoasis
    Commented Jul 21, 2014 at 7:00
  • If you have a set pattern on the string 'str', then you can use slit by ('=') to read key and value separately. e.g. str.split('=')[0] , str.split('=')[1]; , Just an short method if you want to avoid Regex.
    – foo-baar
    Commented Jul 21, 2014 at 7:02

2 Answers 2

37

Now, with ES2018, RegExp named capture groups are actually possible.

Here's an example already working in Chrome 64 (soon to be available also in Safari).

const isoDateExpression = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;

let match = isoDateExpression.exec('1999-12-31');
console.log(
    match.groups.year, // 1999
    match.groups.month, // 12
    match.groups.day, // 31
)

Syntax reference: https://github.com/tc39/proposal-regexp-named-groups

Firefox haven't decided yet, but here's an entry in Mozilla's issue tracker: https://bugzilla.mozilla.org/show_bug.cgi?id=1362154

Edit: Named capture groups are now implemented in major browsers and available since Chrome 62 (2018), Firefox 78 (2020) and Safari 11.3 (2018).

5

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.

4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.