212k views
4 votes
How to remove html tags from a string in javascript

1 Answer

3 votes

Final answer:

To remove HTML tags from a JavaScript string, use the replace() function with a regular expression. The pattern /<[^>]*>/g will match.

Step-by-step explanation:

To remove HTML tags from a string in JavaScript, one common method is to use the replace() function combined with a regular expression (regex). Here's a short example:

var stringWithHtml = "";
var stringWithoutHtml = stringWithHtml.replace(/<[^>]*>/g, '');
console.log(stringWithoutHtml); // Outputs: Hello World!

This code snippet declares a variable stringWithHtml that contains HTML content. It uses the replace() function to find all sequences of characters that start with '<' and end with '>', including everything in between—represented by the regex pattern /<[^>]*>/g.

These sequences are then replaced with an empty string (effectively removing them), resulting in a stringWithoutHtml that contains only the text. Remember that while this method is handy for simple cases, it shouldn't be relied upon for security-related tasks such as sanitizing user input because it may not remove all types of malicious content embedded within HTML.

User Pavel Grigorev
by
7.8k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.