Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top