Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific HTML tag with its content from javascript string

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

like image 214
Gulmuhammad Akbari Avatar asked Jul 23 '17 06:07

Gulmuhammad Akbari


People also ask

Which tag is used to remove all HTML tags from a string?

Definition and Usage. The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped.

How do you remove HTML tags in HTML?

Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

How do I strip a string in HTML?

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.


2 Answers

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>
*/
like image 181
anubhava Avatar answered Nov 14 '22 07:11

anubhava


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);
like image 42
Nisarg Shah Avatar answered Nov 14 '22 06:11

Nisarg Shah