How to remove html tags from a string in JavaScript?


Removing HTML tags from a string

We can remove HTML/XML tags in a string using regular expressions in javascript. HTML elements such as span, div etc. are present between left and right arrows for instance <div>,<span> etc. So replacing the content within the arrows, along with the arrows, with nothing('') can make our task easy.

Syntax

str.replace( /(<([^>]+)>)/ig, '');

Example-1

Live Demo

<html>
<body>
<script>
   function removeTags(str) {
      if ((str===null) || (str===''))
      return false;
      else
      str = str.toString();
      return str.replace( /(<([^>]+)>)/ig, '');
   }
   document.write(removeTags('<html> <body> Javascript<body> is not Java'));;
</script>
</body>
</html>

Output

Javascript is not Java

Example-2

Live Demo

<html>
<body>
<script>
   function removeTags(str) {
      if ((str===null) || (str===''))
      return false;
      else
      str = str.toString();
      return str.replace( /(<([^>]+)>)/ig, '');
   }
   document.write(removeTags('<html> Tutorix is <script> the best <body> e-learning platform'));;
</script>
</body>
</html>

Output

Tutorix is the best e-learning platform

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements