Daniel Cheung
Daniel Cheung

Reputation: 4819

js - match() not returning value correctly

I'm a beginner at regex. Although I used https://www.regex101.com/r/nD8qB4/2 to check my regex, match() isn't returning the value as I want.

js:

"[ls]Something[/ls]".match(/\[ls\](.*?)\[\/ls\]/g)[0];

Output:

[ls]Something[/ls]

What I want:

Something

Where's my problem? Here's a jsfiddle: http://jsfiddle.net/6b7a2z8d/

Upvotes: 0

Views: 282

Answers (1)

zerkms
zerkms

Reputation: 254916

Your problem is caused by using g modifier.

It disables using the capturing groups.

So you need:

  1. remove g
  2. access [1] index instead

It returns 2 values because:

  • Value indexed 0 is the total match the whole regular expression captures
  • 1..N matches per each capturing group

In your case it is possible to get only one match:

(?<=\[ls]).*?(?=\[\/ls])

Major differences compared to your regex:

  1. There is no dedicated capturing group for the middle part (since we don't want it)
  2. Pre- and post- assertions are replaced with a special regex assertions syntax that means "text preceded by" and "text followed by". And as it follows from their name, they only assert some constraint but don't form the new match.

IMPORTANT: as it was noted in the comments below, the proposed solution will not work with JS, since its regular expression implementation does not support lookbehind assertions.

Upvotes: 3

Related Questions