Morse
Morse

Reputation: 9144

Regex not working for multiple characters

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

C# version

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_);

Typescript Version

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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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:

  • The - 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
  • Rather than using callback methods, in order to reference the whole match, you may use the $& placeholder in a string replacement pattern
  • When you define the regex using a regex literal, there is only one backslash needed to form a regex escape, so const regexM = /[\\`*_{}[\]()#+.!|-]/g is equal to const regexM = new RegExp("[\\\\`*_{}[\\]()#+.!|-]", "g")
  • There is no need to check if there is a line break char or not with if (/\r|\n/.exec(inputString)), just run .replace.

Upvotes: 1

Related Questions