给出如下的全文:
var nation = "Piazza delle Medaglie d'Oro
40121 Bologna
Italy"
一个给定的数组如:
["Afghanistan", "Italy", "Albania", "United Arab Emirates"]
我们如何检查整个文字中的 意大利 一词是否在array
?
遵循此SO answer这是我尝试过的,但是我得到了False
,而{strong> 意大利 出现在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);
});
答案 0 :(得分:5)
如果您在推送数组时检查它,它甚至更简单,只需检查推送的元素:
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);
}
如果你仍想每次检查整个数组,嵌套迭代可能会这样做:
let countries = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"];
const text = " I like Italy";
let countriesInText = countries.filter( word => text.includes( word ) );
//["Italy"]
Performance compared to Rajeshs answer
如果您只关心是否,可以使用 .some()而不是 .filter()。
答案 1 :(得分:3)
由于您需要在数组中搜索包含单词的字符串,因此最好选择使用正则表达式并使用string.match(regex)
来获取匹配的单词。
var nation = `Piazza delle Medaglie d'Oro
40121 Bologna
Italy`;
//var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy";
var countries = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"];
var regex = new RegExp(countries.join("|"), "i");
console.log(nation.match(regex))

答案 2 :(得分:0)
var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy";
searchStringInArray("Italy", nation);
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
答案 3 :(得分:0)
此脚本会将var var中的每个单词与您提供的所有数组元素进行比较。我希望这能解决你的问题
<script>
var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy";
test = nation.split(" ");
array = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"];
test.forEach(function (element) {
array.forEach(function (array_to_compare) {
if (element == array_to_compare)
alert("We found that word " + element + " matches in array");
});
}, this);
each()
</script>
答案 4 :(得分:0)
$(function () {
try {
var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy";
var I = ["Afghanistan", "Italy", "Albania", "United Arab Emirates"]
for (var index = 0; index < I.length; index++) {
if (nation.toString().toUpperCase().indexOf(I[index].toString().toUpperCase()) >= 0) {
console.log(I[index].toString());
}
}
}
catch (err) {
console.log(err);
}
});
尝试这个。