admin管理员组文章数量:1316336
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?
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?
Share Improve this question edited Jun 26, 2015 at 16:13 Wiktor Stribiżew 628k41 gold badges498 silver badges611 bronze badges asked Jun 26, 2015 at 14:13 mottossonmottosson 3,7835 gold badges39 silver badges82 bronze badges 2-
You're not capturing the pattern match. use
/^(#[0-9]*=)/
– Joseph Marikle Commented Jun 26, 2015 at 14:16 - you aren't declaring any capture groups. – Daniel A. White Commented Jun 26, 2015 at 14:16
2 Answers
Reset to default 9You 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.
"#2=".replace(/^(#[0-9]*=)/,"<a href='$1'>$1</a>")
wrap group to ()
本文标签: javascriptRegex to wrap strings with HTML tagsStack Overflow
版权声明:本文标题:javascript - Regex to wrap strings with HTML tags - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742003786a2411550.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论