Remove specific HTML tag with its content from javascript string

Solution 1:

You should avoid parsing HTML using regex. Here is a way of removing all the <a> tags using DOM:

// your HTML text
var myString = '<table><tr><td>Some text ...<a href="#">label...</a></td></tr></table>';
myString += '<table><tr><td>Some text ...<a href="#">label...</a></td></tr></table>'
myString += '<table><tr><td>Some text ...<a href="#">label...</a></td></tr></table>'

// create a new dov container
var div = document.createElement('div');

// assing your HTML to div's innerHTML
div.innerHTML = myString;

// get all <a> elements from div
var elements = div.getElementsByTagName('a');

// remove all <a> elements
while (elements[0])
   elements[0].parentNode.removeChild(elements[0])

// get div's innerHTML into a new variable
var repl = div.innerHTML;

// display it
console.log(repl)

/*
<table><tbody><tr><td>Some text ...</td></tr></tbody></table>
<table><tbody><tr><td>Some text ...</td></tr></tbody></table>
<table><tbody><tr><td>Some text ...</td></tr></tbody></table>
*/

Solution 2:

Here's the code. The regex /<a.*>.*?<\/a>/ig fits well for your data.

var myString = "<table><tr><td>Some text ...<a href='#'>label...</a></td></tr></table>";
myString += "<table><tr><td>Some text ...<a href='#'>label...</a></td></tr></table>";
myString += "<table><tr><td>Some text ...<a href='#'>label...</a></td></tr></table>";

console.log(myString);

var anchorTagsRemoved = myString.replace(/<a.*?>.*?<\/a>/ig,'');
console.log(anchorTagsRemoved);