[英]How do I match a string to a regex using Lodash?
I'm unable to successfully match a string to a regex using Lodash.我无法使用 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?有谁知道如何使用 Lodash 匹配正则表达式参数?
Why don't you use vanilla JS for this?你为什么不为此使用香草JS?
var regex = /foo/; var string = "foo"; console.log(regex.test(string))
_.invoke
is the correct function to use, but your syntax is slightly wrong. _.invoke
是正确的 function 使用,但您的语法略有错误。 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.看看文档: arguments 调用方法(第三个参数
invoke
)不在数组中,在您的情况下, path
参数(第二个参数invoke
)也是一个简单的字符串。 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);
you can just do it in plain Javascript.你可以用普通的 Javascript 来做。 Try
尝试
const regex = /foo/;
const testString = "bar";
if(regex.test(testString)) {
// code..
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.