2

I have to check if a string contains some special character, and if it does, add a backslash to it.

var spChar=['%','^','!'];

If string is "This contains % and ^ characters".
I want to make it "This contains \% and \^ characters".

I dont want to loop through all the characters. Is there anyway i can achieve this by using regex

Zaid Bin Irfan
  • 330
  • 1
  • 13

1 Answers1

5

You can use a regex like

"This contains % and ^ characters".replace(/([%^!])/g, '\\$1')

But if you are looking to escape regex, you can use a function like

if (!RegExp.escape) {
    RegExp.escape = function (s) {
        return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
    };
}

//then
var newstring = RegExp.escape(mystring)
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531