admin管理员组文章数量:1322361
I have the following string:
This *is* a *test*!
I want to bold the words surrounded by the * characters (so "is" and "test" in the example).
I have the following JavaScript code:
var data = "This *is* a *test*!";
return data.replace(/\*(.*)\*/g, <b>$1</b>);
When the string is returned, I get the following:
This <b>is* a *test</b>!
How can I change the pattern or basic code in order to do the replacement the way I want it?
I have the following string:
This *is* a *test*!
I want to bold the words surrounded by the * characters (so "is" and "test" in the example).
I have the following JavaScript code:
var data = "This *is* a *test*!";
return data.replace(/\*(.*)\*/g, <b>$1</b>);
When the string is returned, I get the following:
This <b>is* a *test</b>!
How can I change the pattern or basic code in order to do the replacement the way I want it?
Share Improve this question asked Jun 17, 2009 at 21:39 JamesEggersJamesEggers 12.9k14 gold badges65 silver badges89 bronze badges2 Answers
Reset to default 5SO messed with my HTML...
var result = "This *is* a *test*!".replace(/\*(.*?)\*/gi, "<b>$1</b>");
You need to make the pattern non-greedy by adding the ?-operator after the *:
var data = "This *is* a *test*!";
return data.replace(/\*(.*?)\*/g, "<b>$1</b>");
Here is a reference for JavaScript RegExp from Mozilla Developer Center.
本文标签: regexHandling Multiple JavaScript Replace MatchesStack Overflow
版权声明:本文标题:regex - Handling Multiple JavaScript Replace Matches - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742111233a2421265.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论