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

fox*_*xer 3 javascript

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

}
Run Code Online (Sandbox Code Playgroud)

StackOverflow 上有很多答案,但我找不到可行的解决方案。

笔记:

let expect = 'i was sent' 
let entry = 'to earth i was sent'
Run Code Online (Sandbox Code Playgroud)

应该返回 true

let expect = 'i was sent' 
let entry = 'i was sente to earth'
Run Code Online (Sandbox Code Playgroud)

应该返回 false

小智 8

似乎您正在谈论匹配单词边界,这可以使用匹配单词边界的断言来完成,所以\b您可以: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
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 :)