user409
user409

Reputation: 115

remove a specific string from an object in an array

i have a data as below;

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',
  },
];

I want to remove every "<span class="searchmatch">" and it's correlated "</span>" from all of them with split&join || replaceAll method but i couldn't reach all objects with for loop, how can i do it? Thanks.

Upvotes: 0

Views: 59

Answers (1)

Sarah Gro&#223;
Sarah Gro&#223;

Reputation: 10879

You can use Array.prototype.map to apply a function on all elements of an array. In that function, you can use either use String.prototype.replaceAll or a full regular expression to replace those tags.

(see here on why it's generally a bad idea to handle HTML with RegEx; but in this case, if you can be sure that the tags will always be written exactly that way, and you're not actually parsing anything but simply replacing strings, I think it's OK here!)

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);

Upvotes: 1

Related Questions