【问题标题】:How to search more than one word in a sentence using javascript如何使用javascript在一个句子中搜索多个单词
【发布时间】:2019-02-01 17:32:47
【问题描述】:

下面的代码在句子中搜索特定单词(最佳),并根据结果返回真或假。

现在我需要升级以允许它搜索 multiple 单词。 “网站、所有、世界”

var myString = 'Stackoverflow is the best site for all developers in the world';

var multiple_Word = 'best';
var a = new RegExp('\\b' + multiple_Word + '\\b');
alert (a.test(myString)); // false

【问题讨论】:

  • 我根本不清楚你在问什么。预期的输入和输出是什么?
  • best|site|world 是你要找的东西。虽然@jonrsharpe 有一点,也许是必须包含所有单词?
  • 您好 JonrSharpe。如果在句子中找到三个单词中的任何一个,我需要它返回 true,如果在句子中不存在这三个单词,则返回 false

标签: javascript


【解决方案1】:

您可以扩展代码并将其更改为函数。

var myString = 'Stackoverflow is the best site for all developers in the world';

function search(input){
  var a = new RegExp('\\b' + input + '\\b');
  return a.test(myString)
}

console.log(['site', 'all', 'world', 'blah blah'].some(e=>search(e)))

您可以在您提到要匹配其中一个的评论中使用加入。

var myString = 'Stackoverflow is the best site for all developers in the world';
const words1 = ['best', 'site', 'random'];

let reg = `\b${words1.join('|')}\b`
let regex = new RegExp(reg)

console.log(regex.test(myString))

【讨论】:

    【解决方案2】:

    这里有一个很好的正则表达式资源:https://regex101.com/ 添加blah进行演示。

    var myString = 'Stackoverflow is the best site for all developers in the world';
    
    var multiple_Word = 'best|BLAH|world';
    var a = new RegExp('\\b' + multiple_Word + '\\b');
    alert (a.test(myString)); // false

    【讨论】:

      【解决方案3】:

      使用 Array#join 和 |

      const str = 'Stackoverflow is the best site for all developers in the world';
      
      const words1 = ['best', 'site', 'random'];
      const words2 = ['will', 'fail', 'always'];
      
      const a = new RegExp('\\b' + words1.join("|") + '\\b');
      const b = new RegExp('\\b' + words2.join("|") + '\\b');
      
      console.log(a.test(str));
      console.log(b.test(str));

      【讨论】:

        【解决方案4】:

        这是使用includes() 执行此操作的示例

        let words = ["the","best","world"];
        let words2 = ["the","best","world","apple"];
        var myString = 'Stackoverflow is the best site for all developers in the world';
        function checkWords(str,words){
          for(let word of words){
            //if the word in words arr doesnot exist is str it will return false
            if(!str.includes(word)) return false
          }
          //if false is not return in loop it means all words exist is str so return true 
          return true;
        }
        console.log(checkWords(myString,words));
        console.log(checkWords(myString,words2));

        【讨论】:

          猜你喜欢
          • 2019-12-02
          • 1970-01-01
          • 2021-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-29
          相关资源
          最近更新 更多