javascript - 从数组中的对象中删除特定字符串
问题描述
我有如下数据;
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 循环访问所有对象,我该怎么做?谢谢。
解决方案
您可以使用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);
推荐阅读
- javascript - setInterval 没有更新我的时钟时间。手动刷新页面时时间显示和刷新
- javascript - 如何从数组元素中获取不同的组合?
- scala - SCALA - 子类型声明中的大括号
- reactjs - 在 React Web App 中存储授权令牌
- sql - 从特定记录/项目键分页开始获取范围
- optimization - 最小化函数和的最大值
- php - Zend 条形码 PNG 输出在 Codeigniter 中给我 500 个内部错误
- java - opencsv 在集合的开始和结束处添加分隔符
- python - 使用 mdtraj 计算二面角
- android - 我无法在 Android Studio 上构建我的项目,因为 JCenter 崩溃了: