Skip to content
Advertisement

Regex bold characters using *

If I have text like:

I need to bold *this* text and *that* text.

I need to bold this text and that text.

I need to convert both to <b>this</b> and <b>that</b>.

var str = $('textarea#commentfield').val();
var getBold = str.match(/*.+*/g);
if(getBold!=null){
  getBold = getBold.toString().replace(/*/g,"");
}
str = str.replace(/*[^*]+?*/g, "<b>"+getBold+"</b>");

This is not doing what I want for 2 or more matches. It’s doing this instead:

I need to bold this text and that text and this text and that text.

Advertisement

Answer

You can just use a capture group and a group reference number :

str =str.replace(/*([^*]+)*/g, "<b>$1</b>");
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement