javascript - Need help parsing markdown, remove italic (*) but not bold(**) -
i trying replicate wmd markdown editor. tried modify wmd instead of reinventing wheel code not readable me ...
so trying allow removing of italics "*
" not bold "**
"
so, italics below should removed
this *is a* test ***is a*** test
but below should untouched
this **is a** test
i guess should use regexp
how? how match *
if "alone" or followed 2 or more *
s
this hard solve straight regexp, handling edge cases asterisks @ beginning or end of string. mixing regexp magic replace magic gets 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")); // test alert(removeitalics("this **is a** test")); // **is a** test alert(removeitalics("this ***is a*** test")); // test
we're matching runs of 1 or more asterisks. matches greedy. longest run of asterisks matched. if length of match 2, put asterisks back, otherwise strip them.
working example here: http://jsfiddle.net/qknam/
update: if want keep bold if have 2 or more asterisks, change match.length logic this...
function removeitalics(str) { var re = /\*+/g; return str.replace(re, function(match, index) { return match.length === 1 ? '' : '**'; }); } alert(removeitalics("this *is a* test")); // test alert(removeitalics("this **is a** test")); // **is a** test alert(removeitalics("this ***is a*** test")); // **is a** test
updated jsfiddle: http://jsfiddle.net/qknam/3/
Comments
Post a Comment