Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not this string pass test function?

This is what I do:

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 does not. I wonder, what I'm doing wrong?

like image 993
Jacobian Avatar asked Jan 24 '26 22:01

Jacobian


2 Answers

You have to escape all parenthesis, and you are not. Adding the \\ to the ( on the input string 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

would work.

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

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 demo fiddle.

like image 144
acdcjunior Avatar answered Jan 26 '26 10:01

acdcjunior


Because you do not escape the ( and ) which makes them capture groups. Also the period also needs to be escaped so it is not a match anything 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
like image 33
epascarello Avatar answered Jan 26 '26 11:01

epascarello