Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to wrap strings with HTML tags

I have a textarea with lots of lines that look like:

#1=stuff
#2=more stuff
...
#123=even more stuff
...

I'm using regex to find the #num= pattern (/^#[0-9]*=/) and I want to make them anchor tags like

<a href='#123='>#123=</a>

But it won't work as I thought it would.

"#2=".replace(/^#[0-9]*=/,"<a href='$1'>$1</a>")

The result:

<a href='$1'>$1</a>

What am I doing wrong?

like image 892
mottosson Avatar asked Jun 26 '15 14:06

mottosson


2 Answers

You forget about capturing groups or to refer to the 0th group with $& and you only handle the initial number because you are using a start of string anchor (you need to remove it to match all of them, or use a multiline flag if you want to match beginning of lines):

/^#[0-9]*=/m

Replace with $&.

See demo

Results:

<a href='#1='>#1=</a>stuff
<a href='#2='>#2=</a>more stuff
...
<a href='#123='>#123=</a>even more stuff

Just note that backreferences in the replacement string can only be evaluated when there are capturing groups set, otherwise they are treated as literal strings in the replacement.

like image 192
Wiktor Stribiżew Avatar answered Oct 06 '22 13:10

Wiktor Stribiżew


"#2=".replace(/^(#[0-9]*=)/,"<a href='$1'>$1</a>")

wrap group to ()

like image 38
Vasiliy Vanchuk Avatar answered Oct 06 '22 13:10

Vasiliy Vanchuk