【问题标题】:Check if a string contains exact match检查字符串是否包含完全匹配
【发布时间】:2020-02-27 19:05:35
【问题描述】:

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

应该返回假

【问题讨论】:

  • 你想看看它是否包含或完全匹配?
  • stackoverflow.com/a/447258/5132337 它给出了正确答案。
  • let expect = 'i was sent' let entry = 'i was sent e to earth' // 应该返回 false 或 true
  • 嗯所以entry === expect?
  • @foxer “完全匹配”是否意味着它所说的,或者它是否只是 包含 该字符串也会返回真实?我有点困惑....您是否想真正匹配一个字符串,或者您是否正在寻找正则表达式来识别作为 arg 传递的字符串中某处的特定字符串?

标签: javascript


【解决方案1】:

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

希望对你有帮助:)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      相关资源
      最近更新 更多