Reputation: 3
I'm unable to successfully match a string to a regex using Lodash.
I've would attempt the following code example:
regex = /foo/;
// ele.id might be undefined
_.result(ele.id, 'match(regex)');
_.invoke(ele.id, ['match'], [regex]);
_.invoke(ele.id, ['match'], ['regex']);
Does anyone know how to string match a regex argument using Lodash?
Upvotes: 0
Views: 3827
Reputation: 988
_.invoke
is the correct function to use, but your syntax is slightly wrong. Take a look at the docs: The arguments to invoke the method with (3rd parameter of invoke
) are not in an array, and in your case the path
argument (2nd parameter of invoke
) is a simple string, too. This is how to do it:
// A string
let string = "foo";
// A matching regex (not the case in the original post)
let regex = /foo/;
// Does it match? Note there's two pairs of []
// that shouldn't be there in the original post.
let result = _.invoke(string, "match", regex);
// ["foo"]
console.log(result);
Upvotes: 0
Reputation: 167
you can just do it in plain Javascript. Try
const regex = /foo/;
const testString = "bar";
if(regex.test(testString)) {
// code..
}
Upvotes: 0
Reputation: 3643
Why don't you use vanilla JS for this?
var regex = /foo/;
var string = "foo";
console.log(regex.test(string))
Upvotes: 2