How to use split() and join() method In Javascript

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.

How to Remove HTML Tags from a String in JavaScript?

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:

Table of Content

  • Using Regular Expressions
  • Using split() and join() method

Similar Reads

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....

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....

Contact Us