Why isn't this line skipping the test function?

This is what I am doing:

var input_string = "(1) (1) test.txt";
var reg = new RegExp('^\\(\\d+\\)\\s+' + input_string,'i');
var tested_string = "(1) (1) (1) test.txt";
alert(reg.test(tested_string)); // returns false

      

I expect it to return true, but it doesn't. I wonder what I am doing wrong?

+3


source to share


2 answers


You need to escape all parentheses, and you don't. Adding \\

in (

on the input line would make it work:

var input_string = "\\(1\\) \\(1\\) test.txt"; // fixed
var reg = new RegExp('^\\(\\d+\\)\\s+' + input_string,'i');
var tested_string = "(1) (1) (1) test.txt";
alert(reg.test(tested_string)); // returns true now

      

will work.

If you need to use arbitrary strings in a regular expression, you need to output them. I suggest you use a function like the one below before adding it to the object RegExp

:



function escapeRegExp(stringToGoIntoTheRegex) {
    return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

      

In your case, it could be like:

var input_string = "(1) (1) test.txt";
var reg = new RegExp('^\\(\\d+\\)\\s+' + escapeRegExp(input_string),'i'); // using it here
var tested_string = "(1) (1) (1) test.txt";
alert(reg.test(tested_string)); // returns true as expected

      

See the demo script .

+6


source


Because you don't avoid (

and )

that make them grab groups. In addition, this period must also be screened, so it does not match anything in character.



    var input_string = "\\(1\\) \\(1\\) test\\.txt";
    var reg = new RegExp('^\\(\\d+\\)\\s+' + input_string,'i');
    var tested_string = "(1) (1) (1) test.txt";
    alert(reg.test(tested_string)); // returns false
      

Run codeHide result


+5


source







All Articles