Reputation: 51
I'm trying to bold the text between *
, like *bold*
I'm trying regular expressions in JavaScript but I don't know why its not working.
var bold = /\*(.*?)\*/gim;
var replacedText = replacedText.replace(bold, function($0,$1){
return $1?$0:'<b>' + $0 + '</b>';
});
Thank you guys here is final Answer
Edited
var bold = /\*(.*?)\*/gim;
var replacedText = replacedText.replace(bold, function($0,$1){
return $1 ? ('<b>' + $1 + '</b>') : $0;
});
Upvotes: 4
Views: 1044
Reputation: 147363
Something like:
function makeBold(id) {
var re = /(\*)([^*]*)(\*)/g;
var el = document.getElementById(id);
el.innerHTML = el.innerHTML.replace(re, '<b>$2</b>');
}
should get you started.
Upvotes: 1
Reputation: 437336
The regex is OK, but your logic is not:
var replacedText = replacedText.replace(bold, function($0,$1){
return $1 ? ('<b>' + $1 + '</b>') : $0;
});
The condition was inverted, and in any case you should be using $1
when replacing instead of $0
(the latter includes the asterisks).
Upvotes: 5