Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
*/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...