I have a body of text that I’m searching using JavaScript. I let the user specify an arbitrary string, then I want to search for that string, with the condition that it is treated as a “whole words”, i.e. is between word boundaries.
I just want to be able to say e.g.
var userString = "something blah";
// => "blah another thing blah"
"blah something blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
// no match, good
"blahsomething blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
userString = "something\\blah";
// want to match, but doesn't
"blah something\\blah blah".replace(new RegExp("\\b" + userString + "\\b"), "another thing");
As you can see, it breaks down for special characters — I need a way to tell the RegExp to escape user input, or to set aside a part of the expression as a literal. Is this possible in JavaScript?
1 Answer