Javascript Regex : Remove Text Between Html Tags
Title
Solution 1:
If, as your question suggests, you want to remove all text from between any HTML tags… only the real DOM is going to cut it.
function removeAllTextNodes(node) {
if (node.nodeType === 3) {
node.parentNode.removeChild(node);
} else if (node.childNodes) {
for (var i = node.childNodes.length; i--;) {
removeAllTextNodes(node.childNodes[i]);
}
}
}
This, unlike textContent
and innerHTML
, will keep all existing element structure in place and remove only text.
If you really have a string and are using client-side JavaScript in a browser, and the string represents part of a document’s content (and not an entire document – i.e. you won’t find any DTD, <html>
, <head>
, or <body>
elements within), then you can parse it just by putting it into an element:
var container = document.createElement("div");
container.innerHTML = htmlString;
removeAllTextNodes(container);
return container.innerHTML;
Otherwise, you’ll probably want an HTML parser for JavaScript. Regular expressions, as it’s been noted, aren’t great at parsing HTML.
Solution 2:
VANILLA JS TO THE RESCUE
var x = document.getElementsByTagName("h1");
for (var i=0; i<x.length; i++) {
x[i].innerHTML = "";
}
Just insert any tag you'd like and wallah, no need for regex, or a 90kb library.
Solution 3:
Javascript is already able to accomplish this with built in functions in a way that in conceptually superior to regex
<div><h1id="foo">Title</h1></div><script>document.getElementById("foo").textContent = ""</script>
Solution 4:
You would probably want to do something like this;
var elements = document.getElementsByTagName('*');
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
if(element.children.length === 0) {
elements[i].textContent = '';
}
}
This
- Finds all elements
- Loops through them
- Removes any text content
Docs:
You can also make this re-usable like so
var removeAllText = function() {
var elements = document.getElementsByTagName('*');
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
if(element.children.length === 0) {
elements[i].textContent = '';
}
}
}
Then whenever you want you can do this
removeAllText();
Solution 5:
Don't use regex. Use something like loadXMLDoc() to parse the DOM and print the tags, instead of trying to remove the values from within the tags.
Post a Comment for "Javascript Regex : Remove Text Between Html Tags"