繁体   English   中英

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

[英]Check if a string contains exact match

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

应该返回真

let expect = 'i was sent' 
let entry = 'i was sente to earth'

应该返回false

好像你在谈论匹配单词边界,可使用实现\\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

希望能帮助到你 :)

我尚未对此进行测试,但您需要将预期转换为字符串数组,然后检查所有项目是否都在条目字符串中。

let arr = expect.split(" ");
if (arr.every(item => entry.includes(item)) {
  console.log("match");
}
else.....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM