我想检查字符串(let entry)是否包含与let expect完全匹配的字符串。
let expect = 'i was sent'
let entry = 'i was sente to earth' // should return false
// let entry = 'to earth i was sent' should return true
// includes() using the first instance of the entry returns true
if(entry.includes(expect)){
console.log('exact match')
} else {
console.log('no matches')
}
在StackOverflow上有很多答案,但我找不到一个可行的解决方案。
注:
let expect = 'i was sent'
let entry = 'to earth i was sent'应该返回true
let expect = 'i was sent'
let entry = 'i was sente to earth'应该返回假
发布于 2020-02-27 19:28:07
似乎您正在讨论匹配的单词边界,这可以在与单词边界匹配的RegExp中使用RegExp断言来完成,因此可以这样做:
const escapeRegExpMatch = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
const isExactMatch = (str, match) => {
return new RegExp(`\\b${escapeRegExpMatch(match)}\\b`).test(str)
}
const expect = 'i was sent'
console.log(isExactMatch('i was sente to earth', expect)) // <~ false
console.log(isExactMatch('to earth i was sent', expect)) // <~ true
希望它有帮助:)
发布于 2020-02-27 19:25:11
我还没有对此进行测试,但您需要将预期的字符串转换为字符串数组,然后检查条目字符串中是否包含所有项。
let arr = expect.split(" ");
if (arr.every(item => entry.includes(item)) {
console.log("match");
}
else.....https://stackoverflow.com/questions/60440139
复制相似问题