
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Strip Out HTML Tags from a String Using JavaScript
We can strip out HTML tags from a string with JavaScript using the following examples ?
- Strip out HTML tags using Regex
- Strip out HTML tags using InnerText
Strip out HTML tags using Regex
The regex will identify the HTML tags and then the replace() is used to replace the tags with null string. Let's say we have the following HTML ?
<html><head></head><body><p>The tags stripped...<p</body></html>
We want to remove the above tags with Regular Expression. For that, we will create a custom function ?
function removeTags(myStr)
The myStr will have our HTML code for which we want to remove the tags ?
function removeTags(myStr) { if ((myStr===null) || (myStr==='')) return false; else myStr = myStr.toString(); return myStr.replace( /(<([^>]+)>)/ig, ''); }
The call for the above function to remove tags goes like this ?
document.write(removeTags('<html><head></head><body><p>The tags stripped...<p</body></html>'));;
Example
Let us now see the complete example ?
<!DOCTYPE html> <html> <title>Strip HTML Tags</title> <head> <script> function removeTags(myStr) { if ((myStr===null) || (myStr==='')) return false; else myStr = myStr.toString(); return myStr.replace( /(<([^>]+)>)/ig, ''); } document.write(removeTags( '<html><head></head><body><p>The tags stripped...<p</body></html>'));; </script> </head> <body> </body> </html>
Output

Strip out HTML tags using InnerText
Example
In this example, we will strip the HTML tags using innerText ?
<!DOCTYPE html> <html> <title>Strip HTML Tags</title> <head> <script> var html = "<html><head></head><body><p>The tags stripped...<p</body></html>"; var div = document.createElement("div"); div.innerHTML = html; var text = div.textContent || div.innerText || ""; document.write(text) </script> </head> <body> </body> </html>
Output

Advertisements