Javascript 如何使用Lodash将字符串与正则表达式匹配?

Javascript 如何使用Lodash将字符串与正则表达式匹配?,javascript,lodash,Javascript,Lodash,我无法使用Lodash将字符串与正则表达式成功匹配 我将尝试以下代码示例: regex = /foo/; // ele.id might be undefined _.result(ele.id, 'match(regex)'); _.invoke(ele.id, ['match'], [regex]); _.invoke(ele.id, ['match'], ['regex']); 有人知道如何使用Lodash字符串匹配正则表达式参数吗?为什么不使用vanilla JS呢 var reg

我无法使用Lodash将字符串与正则表达式成功匹配

我将尝试以下代码示例:

regex = /foo/;

// ele.id might be undefined
_.result(ele.id, 'match(regex)');
_.invoke(ele.id, ['match'], [regex]);
_.invoke(ele.id, ['match'], ['regex']);

有人知道如何使用Lodash字符串匹配正则表达式参数吗?

为什么不使用vanilla JS呢

var regex=/foo/;
var string=“foo”;

console.log(regex.test(string))
为什么不使用vanilla JS呢

var regex=/foo/;
var string=“foo”;

log(regex.test(string))
您只需使用普通Javascript即可。试一试

const regex = /foo/;
const testString = "bar";
if(regex.test(testString)) {
   // code..
}

您只需使用普通Javascript即可。试一试

const regex = /foo/;
const testString = "bar";
if(regex.test(testString)) {
   // code..
}

\ invoke
是正确使用的函数,但语法稍有错误。请看一看:用于调用方法的参数(调用的第三个参数
invoke
)不在数组中,在您的示例中,
path
参数(调用的第二个参数
invoke
)也是一个简单的字符串。这是如何做到的:

// 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);

\ invoke
是正确使用的函数,但语法稍有错误。请看一看:用于调用方法的参数(调用的第三个参数
invoke
)不在数组中,在您的示例中,
path
参数(调用的第二个参数
invoke
)也是一个简单的字符串。这是如何做到的:

// 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);

我修改了我的原始帖子,为我为什么会使用Lodash提供了更好的上下文。我修改了我的原始帖子,为我为什么会使用Lodash提供了更好的上下文。