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?
source to share
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 .
source to share
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
source to share