Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backreference in javascript regex pattern

I can find a lot of information about getting the capture groups of a regex in the javascript replace function, using $1, $2, etc.. But what I really need is a way to backreference a capture group in the regex itself.

I need to match the following three strings with one regex:

<--text-->
<**text**>
<++text++>

where text is actually [a-zA-Z]+.

I have this pattern already in Ruby:

/<([-+*]{2})(.+)\1>/

Never mind that I used (.+) here, but I'm interested to know how I can achieve the \1 backreference in javascript. Any ideas?

like image 896
MarioDS Avatar asked Jul 17 '26 16:07

MarioDS


1 Answers

Could you not just try it? It works the same way:

var regex = /<([-+*]{2})(.+)\1>/;

var str = "<--text-->";
regex.exec(str); // ["<!--text-->", "--", "text"]

str = "<--text**>";
regex.exec(str); // null
like image 116
James Allardice Avatar answered Jul 20 '26 04:07

James Allardice



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!