Search code examples
javascriptstringsearchslash

The search() method in javascript fail to search for "\\ch" in a string containing it


I am trying to find the position of \\ch of a latex code, say foo\\ch but the search method of string fail to do it. For example running the following code:

console.log('foo\\c'.search('\\c')); // expected 3, really get 3
console.log('foo\\ch'.search('\\ch')); // expected 3, but get -1

I suspect the "error" is due to \ch form a special character but I have searched over internet and it seem \ch is not a special character.


Solution

  • When calling search() with a string as an argument it is converted to a regex (see here)

    But new RegExp('\\ch') returns /\ch/ which is the regular expression to match any BackSpace character (\cX matches control character X, see here).

    To achieve what you want use the /\\ch/ regex

    'Foo\\ch'.search(/\\ch/) // returns 3