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>
.
JavaScript
x
7
1
var str = $('textarea#commentfield').val();
2
var getBold = str.match(/*.+*/g);
3
if(getBold!=null){
4
getBold = getBold.toString().replace(/*/g,"");
5
}
6
str = str.replace(/*[^*]+?*/g, "<b>"+getBold+"</b>");
7
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 :
JavaScript
1
2
1
str =str.replace(/*([^*]+)*/g, "<b>$1</b>");
2