How to remove html tags from a string in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

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
raja
Published on 19-Jun-2019 15:31:30
Advertisements