Joe Half Face
Joe Half Face

Reputation: 2333

JavaScript regex group targeting

I need to catch word in some standard string (link id actually), but not to catch all string.

This

(?:color_form_submit_)(\w+)

works in ruby and catches yellow in color_form_submit_yellow

But in JS it seems to catch all string, I can't figure out why.

Upvotes: 0

Views: 84

Answers (4)

georg
georg

Reputation: 214959

Unfortunately, JS doesn't support lookbehinds and failed match returns null, not an empty array. So the only way to do that in one expression, without if conditions, is something like

color = (str.match(/color_form_submit_(\w+)/) || []).pop()

Example:

> ("color_form_submit_black".match(/color_form_submit_(\w+)/) || []).pop()
"black"
> ("foo bar".match(/color_form_submit_(\w+)/) || []).pop()
undefined

The advantage of this construct compared to the if statement is that it can be used in an expression context, for example, in a function call:

 myRegex = /color_form_submit_(\w+)/
 showColor((myLabel.match(myRegex) || []).pop())

Upvotes: 3

Christoph
Christoph

Reputation: 51211

var match = string.match(/color_form_submit_(\w+)/);
match && match[1];

would be the shortest (unnecessarily obfuscated) way you can get in javascript.

Upvotes: 0

Paul S.
Paul S.

Reputation: 66334

I wanted to achieve it one regex just for elegance

If you want elegance, then you could try something like this

var str = 'color_form_submit_yellow',
    reg = /color_form_submit_(\w+)/;

(str.match(reg) || [])[1]; // "yellow"

and you also have

('fail'.match(reg) || [])[1]; // undefined

This works because

[1, 2, 3] || []; // [1, 2, 3]
null      || []; // []
array[1] === (array)[1];

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

You need to explicitly look for the match to the first capturing group:

var myregexp = /color_form_submit_(\w+)/;
var match = myregexp.exec(subject);
if (match != null) {
    result = match[1];
}

Upvotes: 1

Related Questions