Reputation: 88189
I am trying to replicate WMD Markdown Editor. I tried to modify WMD instead of reinventing the wheel but its code is not readable to me ...
So I am trying to allow removing of italics "*
" but not bold "**
"
So, the italics below should be removed
this *is a* test
this ***is a*** test
But the below should be untouched
this **is a** test
I guess I should use RegExp
but how? How do I match the *
only if its "alone" or is followed by 2 or more *
s
Upvotes: 4
Views: 1601
Reputation: 11651
This is hard to solve with straight regexp, especially handling edge cases where the asterisks are at the beginning or end of the string. Mixing some regexp magic with some replace magic gets the job done though...
function removeItalics(str) {
var re = /\*+/g;
return str.replace(re, function(match, index) { return match.length === 2 ? '**' : ''; });
}
alert(removeItalics("this *is a* test")); // this is a test
alert(removeItalics("this **is a** test")); // this **is a** test
alert(removeItalics("this ***is a*** test")); // this is a test
We're matching runs of one or more asterisks. Matches are greedy. So the longest run of asterisks will be matched. If the length of the match is 2, we put the asterisks back, otherwise we strip them.
Working example is here: http://jsfiddle.net/QKNam/
UPDATE: If you want to keep bold if you have 2 or more asterisks, just change the match.length logic like this...
function removeItalics(str) {
var re = /\*+/g;
return str.replace(re, function(match, index) { return match.length === 1 ? '' : '**'; });
}
alert(removeItalics("this *is a* test")); // this is a test
alert(removeItalics("this **is a** test")); // this **is a** test
alert(removeItalics("this ***is a*** test")); // this **is a** test
Updated jsFiddle: http://jsfiddle.net/QKNam/3/
Upvotes: 2