如何检查文本中的任何单词是否在数组中? [英] How to check if any word inside a text is in array?

查看:84
本文介绍了如何检查文本中的任何单词是否在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出如下全文:

var nation = "Piazza delle Medaglie d'Oro
40121 Bologna
Italy"

一个给定的数组如:

 ["Afghanistan", "Italy", "Albania", "United Arab Emirates"]

我们如何检查整个文本中的 意大利 一词是否在数组中

How can we check that the word Italy within that whole text is in the array?

按照 SO回答这个是我尝试过的,但我得到 False ,而 意大利 出现在数组中

Following this SO answer this is what I tried, but I get False while instead Italy is present within the array

  var countries = [];
  $("#usp-custom-3 option").each(function() {
    var single = $(this).text();
    countries.push(single);
    var foundPresent = countries.includes("Piazza delle Medaglie d'Oro 40121 Bologna Italy");
    console.log(foundPresent); 
  });

JsFiddle在这里

推荐答案

如果每次推送到数组时检查它,它甚至更简单,只需检查推送的元素:

If you check whenever you push to an array, its even much simpler, just check the pushed element:

const text = " I like Italy";
const nations=[];

function insert(single){
 if( text.includes(single) /*may format single, e.g. .trim() etc*/){
   alert("Nation in text!");
 }
 nations.push(single);
}

运行

如果你还想查看整个数组每次,嵌套迭代都可以做到:

If you still want to check the whole array everytime, a nested iteration may does it:

let countries = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"];
const text = " I like Italy";

let countriesInText = countries.filter( word => text.includes( word ) );
//["Italy"]

运行

性能与Rajeshs回答相比

如果您只关心是否,可以使用 .some()而不是 .filter()

If you just care if or if not, may use .some() instead of .filter().

这篇关于如何检查文本中的任何单词是否在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆