Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex \G + offset equivalent

Is there an equivalent of \G in JavaScript regular expressions? I need to match a pattern at an exact offset. Setting the g flag and .lastIndex searches forward from the given index, but won't match at the offset exactly.

XRegExp has this y modifier which might be what I'm looking for, but it doesn't appear to work in Node/V8.

like image 480
mpen Avatar asked Jun 25 '26 10:06

mpen


1 Answers

I think the only thing you can do is set .lastIndex to your starting point, try a match with .exec(), and then if you get a match check the updated value of .lastIndex. If it's equal to your starting position plus the length of the match result, then the match began exactly where you wanted.

So:

var re = /banana/g;
re.lastIndex = 6;

var mr = re.exec("hello banana");
if (mr[0].length + 6 === re.lastIndex)
  alert("good banana");

I would never claim that this is a "good" way of doing things, it's just the only possibility I know of.

like image 114
Pointy Avatar answered Jun 26 '26 22:06

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!