首页 > 解决方案 > 从数组中的对象中删除特定字符串

问题描述

我有如下数据;

var item = [
  {
    id: 3391396,
    content:
      'D <span class="searchmatch">A</span> (born 17 December 2004) is a swimmer specialized in freestyle swimming. She qualified for the 800m freestyle event of the 2020 Summer',
  },
  {
    id: 49247051,
    content:
      'The footballer <span class="searchmatch">A</span> Demir (born 1979), Macedonian football player <span class="searchmatch">A</span> Irizik (born 1964), Swiss footballer <span class="searchmatch">A</span> Tombak (born 1999),',
  },
  {
    id: 38317336,
    content:
      '<span class="searchmatch">A</span> Selan (born 4 December 1977) is a Macedonian-Turkish stage and screen actor. He was born in Skopje, SR Macedonia, SFR Yugoslavia. He is of Turkish',
  },
];

我想用 split&join || 从所有这些中删除每个“ <span class="searchmatch">”并且它是相关的“ ” </span>replaceAll 方法,但我无法使用 for 循环访问所有对象,我该怎么做?谢谢。

标签: javascript

解决方案


您可以使用Array.prototype.map将函数应用于数组的所有元素。在该函数中,您可以使用 useString.prototype.replaceAll或完整的正则表达式来替换这些标签。

请参阅此处,了解为什么使用 RegEx 处理 HTML 通常是一个坏主意;但在这种情况下,如果您可以确定标签将始终完全按照这种方式编写,并且您实际上并没有解析任何内容,而只是简单地替换了字符串,我觉得这里没问题!)

var item = [{id: 3391396,content: 'D <span class="searchmatch">A</span> (born 17 December 2004) <span class="searchmatch">is</span> a swimmer specialized in freestyle swimming. She qualified for the 800m freestyle event of the 2020 Summer', },{id: 49247051,content: 'The footballer <span class="searchmatch">A</span> Demir (born 1979), Macedonian football player <span class="searchmatch">A</span> Irizik (born 1964), Swiss footballer <span class="searchmatch">A</span> Tombak (born 1999),', },{id: 38317336,content: '<span class="searchmatch">A</span> Selan (born 4 December 1977) is a Macedonian-Turkish stage and screen actor. He was born in Skopje, SR Macedonia, SFR Yugoslavia. He is of Turkish', },];

item.map(i => {
  // if you can be sure that there will never be any other </span> tags in the content
  //i.content = i.content.replaceAll('<span class="searchmatch">', '').replaceAll('</span>', '');
  // otherwise, a regular expression would be the way to go:
  i.content = i.content.replace(/<span class="searchmatch">(.*?)<\/span>/g, '$1');
  return i;
});

console.log(item);


推荐阅读