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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With