
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
Remove HTML Tags with RegExp in JavaScript
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

Advertisements