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:
var regex = new RegExp(keyword);
// if you want it case-insensitive:
var regex = new RegExp(keyword, 'i');
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) != -1
to test if the keyword is in the string or not - without using a regex at all.
Not too sure what exactly you're trying to do here. Javascript does have literal REs so you could just do:
var regex = /foo/;
which is just a nicer way of doing:
var regex = new RegExp( 'foo' );
(but in the second case, the 'foo' could be a string argument being passed in.
You don't need any leading/trailing wildcards on a regular expression.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.