Jacobian
Jacobian

Reputation: 10812

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?

Upvotes: 3

Views: 96

Answers (2)

acdcjunior
acdcjunior

Reputation: 135762

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.

Upvotes: 6

epascarello
epascarello

Reputation: 207511

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

Upvotes: 5

Related Questions