I need to filter an array of string with a wildcard regex:
// my search key
var myKeyword = 'bar';
// my search list
var strings = ['foo', 'bar', 'foobar', 'barfoo', 'hello', 'java', 'script', 'javascript'];
// my results
var results = [];
// the regexp, I don't understand
var regex = new RegExp(\*/, myKeyword);
// the for loop
for (var i = 0; i < strings.length; i++) {
if (regex.test(strings[i]) {
results.push(strings[i]);
}
}
console.log(results); // prints ['bar', 'foobar', 'barfoo']
So how do I fix the regex?
If you want to do it with a regex, do it like this:
This will break if the keyword contains any regex-specific characters such as
[or*. You need to write a function to escape these characters if that’s a problem for you.However, you can solve your problem much easier by using
strings[i].indexOf(keyword) != -1to test if the keyword is in the string or not – without using a regex at all.