Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex Not As Expected

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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);

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading