简体   繁体   中英

Replace word with regex

I have this text: test **test** **test** **test**

and I want to change **test** to <b>test</b> with this code:

var $text = 'test **test** **test** **test**';
$text = $text.replace(/\*\*[^\**]\*\*/,'<b>test</b>');

but i get this output: test **test<b>test</b>test** **test**

jsFiddle

note : between to stars can be anything. (like SO editor)

desired output: test <b>test</b> <b>test</b> <b>test</b>

what is the problem ?

this works:

/\*\*[^\*]*\*\*/g
  1. error: the quantifier star was within the character class
  2. error: you need the global flag g to replace all occurences

jsfiddle: http://jsfiddle.net/fDM3h/1/

code for replacing any content between **:

$text = $text.replace(/\*\*([^\*]*)\*\*/g,'<b>$1</b>');

Use this:

\*\*([^\*]+)\*\*

And replace with capture group $1 like so: http://regex101.com/r/dJ7zG2

Also, you have no reason to use $ in javascript variables like that.

var text = "test **test** **test2** **somethingelse**";
text = text.replace(\*\*([^\*]+)\*\*, "<b>$1</b>");

Result:

"test <b>test</b> <b>test2</b> <b>somethingelse</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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM