Need help disassembling markdowns, delete italics (*), but not bold (**)

I am trying to replicate Markdown Markdown editor. I tried to change WMD, not to reinvent the wheel, but its code cannot be read to me ...

Therefore, I am trying to enable italics " *", but not bold " **"

So, the italics below should be removed

this *is a* test
this ***is a*** test

But below should be untouched

this **is a** test

I think I should use RegExp, but how? How can I compare *only if it is “one” or 2 or more follow it*

+3
source share
1 answer

, , . , ...

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

. . , . 2, , .

: http://jsfiddle.net/QKNam/

UPDATE: , , match.length, ...

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

jsFiddle: http://jsfiddle.net/QKNam/3/

+2

Source: https://habr.com/ru/post/1778029/


All Articles