gpt4 book ai didi

javascript - 检查字符串是否包含完全匹配

转载 作者:行者123 更新时间:2023-11-28 14:08:23 24 4
gpt4 key购买 nike

我想检查字符串(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'

应该返回 false

最佳答案

似乎您正在谈论匹配单词边界,这可以使用 RegExp 中的 \b 断言来完成,该断言匹配单词边界,所以你就可以了:

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

希望有帮助:)

关于javascript - 检查字符串是否包含完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60440139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com