I need to replace a few words on their own in tags. For example
text text text dog text cat text text mouse.
Need to be replaced by <b>dog</b>
or <b>cat</b>
or <b>mouse</b>
if match. I needed to replace it once . If it find word dog means to replace the only dog in <b>dog</ b>
. And nothing more. Even if cat or mouse will be the text.
I have code.
var str = "dog text cat text mouse",
reg = /dog|cat|mouse/;
str = str.replace(reg, '<b>dog</b>').
Sorry, this only replace any of matched with <b>dog</b>
. Help me , please.
Use the g
flag to make a global search instead of just replacing the first occurance.
Use parentheses in the regular expression to catch the match, and use $1
in the replacement to use what you caught.
var str = "dog text cat text mouse";
var reg = /(dog|cat|mouse)/g;
str = str.replace(reg, '<b>$1</b>')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.