I need to remove from HTML line all tags except div and span. How can i do this ?
example
const str = "<div><p></p><span></span></div>";
remove(str)//<div><span></span></div>
The strip_tags() function strips a string from HTML, XML, and PHP tags.
The HTML tags can be removed from a given string by using replaceAll() method of String class. We can remove the HTML tags from a given string by using a regular expression. After removing the HTML tags from a string, it will return a string as normal text.
PHP provides an inbuilt function to remove the HTML tags from the data. The strip_tags() function is an inbuilt function in PHP that removes the strings form HTML, XML and PHP tags. It accepts two parameters. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str.
There are 4 common ways to strip or remove HTML tags in Javascript: Directly extract the text content from an HTML element – var txt = ELEMENT.textContent; Use a library such as String Strip HTML. That should cover the basics, but let us walk through more examples – Read on!
Sanitize a string to make sure there are no HTML tags? There are 4 common ways to strip or remove HTML tags in Javascript: Directly extract the text content from an HTML element – var txt = ELEMENT.textContent; Use a library such as String Strip HTML.
If you assign an ID to the div, you can get the text using document.getElementById ('yourdivIDhere').innerHTML. Thanks for the suggestion, however its not a matter of getting the inner text/html, I want to remove the tags... You can do this.
HTML contained within <body> or <html> or <head> tags is not valid within a <div> and may therefore not be parsed correctly. textContent (the DOM standard property) and innerText (non-standard) properties are not identical. For example, textContent will include text within a <script> element while innerText will not (in most browsers).
To remove all tags excluding specific tags, you can use the following regular expression.
const str = "<div><p></p><span></span></div>";
console.log(str.replace(/(<\/?(?:span|div)[^>]*>)|<[^>]+>/ig, '$1'));
You can use regex /<\/?(?!\bdiv\b)(?!\bspan\b)\b\w+\b>/g
with replaceAll
let str = "<div><oz></oz><span></span><hjk></hjk></div>";
let str1 = str.replaceAll(/<\/?(?!\bdiv\b)(?!\bspan\b)\b\w+\b>/g,'')
console.log(str1);
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