从2个数组中找到匹配的值,一个数组中包含一个html元素-Javascript

我想比较2个数组并从中找到匹配的值,理想情况下,这个问题之前已经被问过,看起来它在我的情况下部分起作用.

让我说我有:

var array1 = ["test-123", "id-859","hi-8098", "hello-9090"];
var array2= ["Welcome <span>test-123</span>", "Welcome33 <span>id-859</span>","How are you <span>hi-8098</span>", "Geat <span>hello-9090</span>", "see ya <span>nono-58758</span>"];

在我的情况下,我有html元素跨度,我想匹配< span>内的值并以o / p返回:

var newArray= ["Welcome", "Welcome33 ","How are you ", "Geat "];

所以基本上array1中的值与array2中的所有值匹配,除了最后一个“see ya< span> nono-58758< / span>”.使用过滤器我可以得到匹配的值,但这些值非常简单,

newArray = array1.filter(e => array2.indexOf(e) !== -1); // in my case its undefined, as it does not recognize the html element in it.

关于如何在数组内部存在html元素时获取匹配值的任何想法?
谢谢!

最佳答案
脚步:

>迭代通过array1
>对于array1中的每个字符串,interate array2
>提取所需的文本以在array1中按字符串搜索(这里我使用拆分)
>将array1中的每个字符串与array2中的每个提取文本进行比较
>如果匹配则推送前文本
>修剪(可选)

var array1 = ["test-123", "id-859","hi-8098", "hello-9090"]
var array2= ["Welcome <span>test-123</span>", "Welcome33 <span>id-859</span>","How are you <span>hi-8098</span>", "Geat <span>hello-9090</span>", "see ya <span>nono-58758</span>"]

let result = []
array1.forEach(searchStr => {
  array2.forEach(dataStr => {
    let stringInTag = dataStr.split('<span>')[1].split('</span>')[0]
    if (searchStr === stringInTag){
      let text = dataStr.split('<span>')[0]
      result.push(text.trim())
    }
  })
})
console.log(result)

转载注明原文:从2个数组中找到匹配的值,一个数组中包含一个html元素-Javascript - 代码日志