I have the following string variable and I want to remove all a
tags with its content from the string.
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>";
I have checked this Remove HTML content groups from start to end of string in JavaScript question's answers but it is for all tags.
Thank you
Definition and Usage. The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped.
Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.
To strip out all the HTML tags from a string there are lots of procedures in JavaScript. In order to strip out tags we can use replace() function and can also use . textContent property, . innerText property from HTML DOM.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With