Reputation: 9144
I want to search and replace special characters of markdown (viz \`*_{}[]()#+.!|-
) from the given string.
I am able to make it work in C# easily since there is verbatim @ but Javascript not getting what's the issue. It seems something to do with /g
, I read in another post which asked to use replaceAll
but I could not find that method for string
string test = @"B
*H*
C
**AB**";
Console.WriteLine ("Input " + test);
var pattern = @"[\\`*_{}\[\]()#+-.!]";
var _1 = Regex.Replace (test, "\r?\n", "<br/>");
var out_ = Regex.Replace (_1, pattern, m => @"\" + m.Value);
Console.WriteLine ("Output " + out_);
const regexM = new RegExp(/[\\\`\*\_\{\}\[\]\(\)#\+-\.!\|]/g, 'm');
var input = `B
*H*
C
**AB**`;
var inputString = input.replace(regexM, function (y: any) { return "\\" + y; });
if (/\r|\n/.exec(inputString))
{
inputString = inputString .replace(/\r?\n/g, "<br/>");
}
inputString = inputString.replace(regexM, function (x: any)
{
return "\\" + x;
});
Expected: B <br/>\*H\*<br/>C<br/>\*\*AB\*\*
I am getting B <br/>\*H*<br/>C<br/>**AB**
Upvotes: 2
Views: 84
Reputation: 627497
You may use
const regexM = /[\\`*_{}[\]()#+.!|-]/g;
var input = `B
*H*
C
**AB**`;
var inputString = input.replace(regexM, "\\$&");
inputString = inputString.replace(/\r?\n/g, "<br/>");
console.log(inputString);
// => B <br/>\*H\*<br/>C<br/>\*\*AB\*\*
NOTE:
-
in the regexM
regex forms a range, you need to either escape it or - as in the code above - put it at the end of the character class$&
placeholder in a string replacement patternconst regexM = /[\\`*_{}[\]()#+.!|-]/g
is equal to const regexM = new RegExp("[\\\\`*_{}[\\]()#+.!|-]", "g")
if (/\r|\n/.exec(inputString))
, just run .replace
.Upvotes: 1