Remove specific HTML tag with its content from javascript string
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>
*/
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);
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>";
el = document.createElement('div');
el.innerHTML = myString;
var output = document.getElementById('output');
el.querySelectorAll('a').forEach(function(item, index){
item.parentNode.removeChild(item);
})
output.innerText = el.innerHTML;
<h3>Output:</h3>
<pre id='output'></pre>