Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 612
Gawdl3y Avatar asked Dec 29 '25 07:12

Gawdl3y


1 Answers

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));
like image 105
qxz Avatar answered Dec 30 '25 23:12

qxz