检查数组中是否有某些字符串(即使有空格)

时间:2018-06-29 17:34:28

标签: javascript jquery html arrays

尝试比较两个数组,看看两个数组中是否都存在现有单词(即使带有空格)。见下文。

我认为我有一个大概的主意。谢谢您的帮助!

HTML

<meta name="keywords" content="dog, cat, humming bird, shark, king cobra">

jQuery

var myArray = $("meta[name='keywords']").attr("content");
var myAnimals = ["humming bird","king cobra"];
if (jQuery.inArray(myAnimals, myArray) != -1) {
    alert('animal exists');
} 

4 个答案:

答案 0 :(得分:2)

attr("content")将返回一个字符串。您可以使用split(',')将字符串转换为数组。使用map遍历数组和trim()空格。

您可以使用some()遍历myArray数组,并使用includes检查数组是否包含特定字符串。

var myArray = $("meta[name='keywords']").attr("content").split(',').map(o => o.trim());
var myAnimals = ["humming bird", "king cobra"];

var result = myArray.some(o => myAnimals.includes(o));
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta name="keywords" content="dog, cat, humming bird, shark, king cobra">


如果要获取实际的数组元素,可以使用filter()includes()

var myArray = $("meta[name='keywords']").attr("content").split(',').map(o => o.trim());
var myAnimals = ["humming bird", "king cobra", "owl"];

var result = myArray.filter(o => myAnimals.includes(o));

console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta name="keywords" content="dog, cat, humming bird, shark, king cobra">

答案 1 :(得分:1)

//split the keywords so it is a real array
var myArray = $("meta[name='keywords']").attr("content").split(', ');
console.log(myArray);

var myAnimals = ["humming bird","king cobra"];

//loop over your animals
myAnimals.forEach(function(animal){
  //check if each animal is in the array
  if (myArray.indexOf(animal) > -1) {
    console.log(animal +' exists!');
  } else {
    console.log(animal +' does not exist!');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta name="keywords" content="dog, cat, humming bird, shark, king cobra">

答案 2 :(得分:0)

更改

var myArray = $("meta[name='keywords']").attr("content");

var myArray = $("meta[name='keywords']").attr("content").split(", ");

然后您的代码应该可以使用。

答案 3 :(得分:0)

.split(', ')上使用keywords创建数组后,
您可以使用函数来获取所有相似的元素:

var myArray = $("meta[name='keywords']").attr("content").split(', ');
var myAnimals = ["humming bird", "king cobra"];

function get_similarities(arrayA, arrayB) {
  var matches = [];
  for (var i = 0; i < arrayA.length; i++) {
    if (arrayB.includes(arrayA[i]))
      matches.push(arrayA[i]);
  }
  return matches;
}

var similarities = get_similarities(myArray, myAnimals);
console.log('Found in both arrays:', similarities);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta name="keywords" content="dog, cat, humming bird, shark, king cobra">

希望有帮助。