-2

I need to strip all the tags containing a specific string, How can I achieve this in javascript?

this is the string

<link rel="stylesheet" href="https://REMOVEME">
<link rel="stylesheet" href="https://ccc">
<link rel="stylesheet" href="https://abc/REMOVEME">
<div>yes</div>

and this the result

<link rel="stylesheet" href="https://ccc">
<div>yes</div>
eeadev
  • 3,662
  • 8
  • 47
  • 100

2 Answers2

0
htmlString.replace(/<link[^>]*href="[^>]*REMOVEME[^>]*"[^>]*>/gi,'')
Carson Liu
  • 86
  • 3
0

Such tasks are better not done with regular expressions.

Instead use the DOM interface available to JavaScript, for instance with this ES6 function:

function removeLinks(html, match) {
    var container = document.createElement('span');
    container.innerHTML = html;
    Array.from(container.querySelectorAll('link[href*=' + CSS.escape(match) + ']'))
        .forEach( link => link.parentNode.removeChild(link) );
    return container.innerHTML;
}

// Sample input
var html = '<link rel="stylesheet" href="https://REMOVEME">' +
           '<link rel="stylesheet" href="https://ccc">' +
           '<link rel="stylesheet" href="https://abc/REMOVEME">' + 
           '<div>yes</div>';

// Remove links that match REMOVEME
html = removeLinks(html, 'REMOVEME');

// Output result
console.log(html);
Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286