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

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Inside escape function, isn't it s.replace(...) instead of value.replace(...)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.