How to remove html tags from a string in JavaScript?

Removing HTML tags from strings is a common task in JavaScript web development. You can accomplish this using regular expressions to match and replace HTML tag patterns with empty strings.

Understanding HTML Tag Structure

HTML elements are enclosed between angle brackets like <div>, <span>, <p>, etc. By targeting the pattern of content within these brackets, we can effectively strip all HTML tags from a string.

Syntax

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

The regular expression /(<([^>]+)>)/ig breaks down as:

  • < - matches opening angle bracket
  • ([^>]+) - matches one or more characters that aren't closing brackets
  • > - matches closing angle bracket
  • i flag - case insensitive matching
  • g flag - global matching (all occurrences)

Method 1: Basic HTML Tag Removal

<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>
Javascript is not Java

Method 2: Handling Complex HTML Structures

<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 </script> <body> e-learning platform</body>'));
</script>
</body>
</html>
Tutorix is  the best  e-learning platform

Method 3: Using DOM Parser (Modern Approach)

<html>
<body>
<script>
   function removeTagsWithDOM(htmlString) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, 'text/html');
      return doc.body.textContent || '';
   }
   
   const htmlText = '<div><p>Hello <strong>World</strong></p></div>';
   document.write(removeTagsWithDOM(htmlText));
</script>
</body>
</html>
Hello World

Comparison

Method Performance Safety Browser Support
Regular Expression Fast Basic All browsers
DOMParser Moderate High Modern browsers

Key Points

  • Regular expressions provide a quick solution for simple HTML removal
  • DOMParser offers better security and handles malformed HTML gracefully
  • Always validate input to prevent unexpected behavior with null or empty strings
  • Consider your use case: regex for performance, DOM methods for safety

Conclusion

Regular expressions offer the fastest way to strip HTML tags, while DOMParser provides a safer approach for complex HTML structures. Choose the method based on your specific requirements for performance and security.

Updated on: 2026-03-15T23:18:59+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements