1

I am trying to write a function which replaces certain words with abbreviations. For example I have the string:

str="Calculate $2\\cdot 2$"

in which I want to replace

"\\cdot" 

with

"*" 

My code looks like this:

str = str.replace(RegExp("\\cdot",'g'),"*");

And the result is

str = "Calculate $2\\cdot 2$"

And I need to use the RegExp function because I have a whole list of words which I want to replace with abbreviations. I know that

str = str.replace(/\\cdot/g),"*");

works. But I don't understand why RegExp doesn't.

1 Answers1

2

You need to escape the slash character when defining a String and once again for the regular expression. If you just escape the slash once in a String, the resulting regex would like this: \cdot. If you define the regular expression directly with the slash notation (/regex/), you would only need to escape it once, because there is no String.

var str = "Calculate $2\\cdot 2$";
str = str.replace(RegExp("\\\\cdot",'g'),"*");
console.log(str);

If you want to generically prepend all the regex special characters with a slash, you can use the following solution, which relies on this answer. You still have to escape the backslash once, because it is part of a String. If you get your String from somewhere, it will be correctly escaped. It's only necessary, if you explicitly write the String into the code (var string = "string";).

var str = "Calculate $2\\cdot 2$";
var regex = "\\cdot";
str = str.replace(RegExp(escapeRegExp(regex), 'g'),"*");
console.log(str);

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
Community
  • 1
  • 1
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
  • Thanks! Thats it! Do you now if there is some way of not needing to use the extra backslash? The problem is that I have a long list of words that I want to replace with abbreviations. Some of them has backslash in them. I could change the words in the list to have the extra backslash but I also want to go back from the abbreviations to the longer words and then it doesn't work. – Johan Tenghamn Jan 14 '17 at 12:33
  • The problem here is, that a regular expression needs backslashes for all control characters like `^` `|` `\` `$` etc. So, if some of your words contain any of these characters, you have to take care of this. I'll update the answer with an extension. – ssc-hrep3 Jan 14 '17 at 13:13