In my web page I have a "find" feature, where the user types in some text in "find" dialog and it gets the index of where the text can be found in a variable. In advance I know neither the text that will be searched, nor the text the user will be looking for. I provide them an option for whether to match case, and whether to find only whole words (e.g. whether "managers" should be a match if they enter "manager".
The following code is a stripped down version of my code with just what is relevant to my issue. In this example, I want to look for "(1)" in "This is a test.(10)". My expectation after execution is that index will be -1, but it is 16, which is the index of the "1".
Can you tell me why this doesn't work and what would work? Thanks.
let matchCase = false;
let wholeWord = false;
let index = 0;
let options = "";
let phrase = "(1)";
phrase = phrase.replaceAll(String.fromCharCode(160), "\\s");
if (!matchCase) options = "i";
if (wholeWord) phrase = "\\b" phrase "\\b";
let regex = new RegExp(phrase, options);
let text = "This is a test.(10)";
let index = text.search(regex);
console.log(index);
CodePudding user response:
You need to escape regular expression metacharacters like (
in the input.
//Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(string) {
return string.replace(/[.* ?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
let matchCase = false;
let wholeWord = false;
let options = "";
let phrase = escapeRegExp("(1)");
phrase = phrase.replaceAll(String.fromCharCode(160), "\\s");
if (!matchCase) options = "i";
if (wholeWord) phrase = "\\b" phrase "\\b";
let regex = new RegExp(phrase, options);
let text = "This is a test.(10)";
let index = text.search(regex);
console.log(index);