Open In App

How to Remove HTML Tags from a String in JavaScript?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Removing HTML tags from a string in JavaScript is a common task, especially when dealing with user-generated content or when parsing HTML data from external sources. HTML tags are typically enclosed in angle brackets and removing them involves extracting only the text content from a string while disregarding any HTML markup.

These are the following methods:

Using Regular Expressions

In this approach, The JavaScript function “removeHtmlTags(input)” uses a regular expression within the “replace()” method to match and replace all HTML tags with an empty string, effectively removing them from the input string “input”. In the usage example, a sample HTML string is passed to the function, resulting in a cleaned string without HTML tags. Finally, the cleaned string is logged to the console.

Example: Removing HTML tags from a string in JavaScript Using Regular Expressions.

JavaScript
function removeHtmlTags(input) {
    return input.replace(/<[^>]*>/g, '');
}

// Usage
const htmlString = '<p>This is a <b>sample</b>
                    paragraph.
                    </p>';
const cleanedString = removeHtmlTags(htmlString);
console.log(cleanedString);

Output
This is a sample paragraph.

Using split() and join() method

In this approach, The JavaScript function utilizes the split() method to break the input string “str” at each HTML tag, creating an array. Then, the “join()” method is applied to concatenate the array elements back into a string, effectively removing the HTML tags. Finally, the cleaned string without HTML tags is returned.

Example: Removing html tags from a string in JavaScript using the split() and join() method.

JavaScript
function removeHtmlTags(str) {
    return str.split(/<[^>]*>/).join('');
}

// Usage
const htmlString = '<p>This is a 
                    <b>sample</b> 
                       paragraph.
                    </p>';
const cleanedString = removeHtmlTags(htmlString);
console.log(cleanedString);

Output
This is a sample paragraph.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads