I'm trying to escape the subset of markdown that Discord supports (*, _, `, ~).
Characters that are already escaped should not have additional backslashes added.
This is what I have:
function escapeMarkdown(text) {
return text.replace(/([^\\]|^|\*|_|`|~)(\*|_|`|~)/g, '$1\\$2');
}
console.log(escapeMarkdown('*test* _string_ ~please~ `ignore` *_`~kthx \* \\~'));
This works fine, minus the fact that multiple markdown characters against each other will not all be escaped. I'm not sure how to expand this to allow for that, without making the expression absurdly complicated.
I would suggest unescaping any already-escaped characters, then escaping everything again:
function escapeMarkdown(text) {
var unescaped = text.replace(/\\(\*|_|`|~|\\)/g, '$1'); // unescape any "backslashed" character
var escaped = unescaped.replace(/(\*|_|`|~|\\)/g, '\\$1'); // escape *, _, `, ~, \
return escaped;
}
var str = '*test* _string_ ~please~ `ignore` *_`~kthx \* \\~ C:\\path\\to\\file';
console.log("Original:");
console.log(str);
console.log("Escaped:");
console.log(escapeMarkdown(str));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With