Reputation: 790
I want to check each values from my array if it matches the string,
however it doesn't work when i'm using console.log(/^reg_arr[i]/.test(str1));
but when I use console.log(/^table/.test(str1));
it works
var str1 = 'table football';
var reg_arr = ["table","football"];
for(var i = 0, reg_arr_length = reg_arr.length; i < reg_arr_length; i++)
{
console.log(/^reg_arr[i]/.test(str1)); /* doesnt work */
}
console.log(/^table/.test(str1)); /* this works */
Is there a problem with my syntax,
Thank you,
Upvotes: 0
Views: 636
Reputation: 707
Using slashes to define a regular expression doesn't allow you to enter variables into the regular expression, that is, in the following example, str1
is checked to contain "test"
, not the value of the variable test.
var str1 = "hello";
var str2 = "Hello world";
console.log(/str1/i.test(str2))
To solve this issue, you need to create a new regular expression for each value in the array, something that can be done with new RegExp(str)
, instead of slashes.
var str1 = "hello";
var str2 = "hello world";
console.log(new RegExp(str1, "i").test(str2))
However, this method has a catch, characters from that string are not escaped. So new RegExp("test.hello")
will match "test hello"
, because the dot is interpreted as a regular expression wildcard character and not a period. To fix that, we first have to manually escape any special characters in our search string (unless the things reg_arr
are actually regular expressions). I took the code to do that from the middle of this MDN page.
var str1 = "hello"
var str2 = "hello world"
str1.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
console.log(new RegExp(str, "i").test(str2))
So without changing anything else, your final console.log
could look like this:
console.log(new RegExp(reg_arr[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).test(str1));
Upvotes: 0
Reputation: 2720
Use new RegExp(source: string[, flags: string])
(simply RegExp(source: string[, flags: string])
is also working)
var str1 = 'table football';
var reg_arr = ["table","football"];
for(var i = 0, reg_arr_length = reg_arr.length; i < reg_arr_length; i++)
{
console.log(new RegExp(`^${reg_arr[i]}`).test(str1));
}
Upvotes: 1