javascript - How to check if any word inside a text is in array? -


given whole text like:

var nation = "piazza delle medaglie d'oro 40121 bologna italy" 

and given array like:

 ["afghanistan", "italy", "albania", "united arab emirates"] 

how can check word italy within whole text in array?

following so answer tried, false while instead italy present within 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 here

if check whenever push array, simpler, check pushed element:

const text = " italy"; const nations=[];  function insert(single){  if( text.includes(single) /*may format single, e.g. .trim() etc*/){    alert("nation in text!");  }  nations.push(single); } 

run


if still want check whole array everytime, nested iteration may it:

let countries = ["afghanistan", "italy", "albania", "united arab emirates"]; const text = " italy";  let countriesintext = countries.filter( word => text.includes( word ) ); //["italy"] 

run

performance compared rajeshs answer

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


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -