Using JS to modify user input for REGEXP search

Viewed 19

I'm taking user input from a searchbar and modifying it to a regexp. From there I can search a json file for valid values and return them. It works fine with input without quotes, but with them, I'm appending "\Q" and "\E" so I can find the entirety of the string (with spaces and other special characters).

if (searchField.includes('"')){
   var tempexpress = searchField.substring(1,searchField.length-1);
   var tempexpress = "\\Q" + tempexpress + "\\E";
   var expression = new RegExp(tempexpress);
   } else {
   var tempexpress = searchField.replace('(',"\\(");
   var tempexpress = tempexpress.replace(')',"\\)");
   var tempexpress = tempexpress.replace(/'/g,"\\'");
   var tempexpress = tempexpress.replace('*',"\.");
   var expression = new RegExp(tempexpress, "i");
   };

if (value.data.label.search(expression) != -1){
    console.log('found it');
}

If I input "QTT6" into the search field (with quotes for a literal), then it creates the following regexp: /\QQTT6\E/

In my testing, I found that it doesn't match to QTT6 for some reason and I'm not sure why. Any help is appreciated.

Also I'm very new to JS and Jquery, so sorry if my code isn't very well put together.

1 Answers

Per Kelly's comment:

In JS you need to use ^ and $ instead of \Q and \E.

For more information, see the MDN docs on Regex Assertions:

^:

Matches the beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A".

Note: This character has a different meaning when it appears at the start of a character class.

$:

Matches the end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, /t$/ does not match the "t" in "eater", but does match it in "eat".

Related