Escaping Discord subset of markdown

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 \*  \\~'));

 Run code snippetExpand snippet

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.

Leave a Comment