w3resource

JavaScript: Remove HTML/XML tags from string

JavaScript String: Exercise-35 with Solution

Remove HTML/XML Tags

Write a JavaScript function to remove HTML/XML tags from a string.

Test Data:
console.log(strip_html_tags('<p><strong><em>PHP Exercises</em></strong></p>'));
"PHP Exercises"

Visual Presentation:

JavaScript: Remove HTML/XML tags from string

Sample Solution:

JavaScript Code:

// Function to strip HTML tags from a given string
function strip_html_tags(str) {
    // Check if the input string is null or empty
    if ((str === null) || (str === '')) {
        // If so, return false
        return false;
    } else {
        // If not, convert the input string to a string type
        str = str.toString();
    }
    // Use a regular expression to replace all HTML tags with an empty string
    return str.replace(/<[^>]*>/g, '');
}

// Test the function with a sample string and log the result to the console
console.log(strip_html_tags('PHP Exercises'));

Output:

PHP Exercises

Explanation:

In the exercise above,

  • The function "strip_html_tags()" takes a single parameter 'str', which represents the input string from which HTML tags will be removed.
  • Inside the function:
    • It first checks if the input string is null or empty. If so, it returns 'false'.
    • If the input string is not null or empty, it converts it to a string type.
    • It then uses a regular expression '(/<[^>]*>/g)' to match and replace all HTML tags (<...>) with an empty string, effectively removing them.
  • Finally, the function returns the modified string with HTML tags removed.

Flowchart:

Flowchart: JavaScript- Remove HTML/XML tags from string

Live Demo:

See the Pen JavaScript Remove HTML/XML tags from string-string-ex-35 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that strips out HTML/XML tags from a string using regular expressions.
  • Write a JavaScript function that removes all tag-like patterns from a string and returns the plain text.
  • Write a JavaScript function that processes a string containing nested tags and returns only the content.
  • Write a JavaScript function that validates the input and ensures no residual tag characters remain after processing.

Go to:


PREV : Convert to Title Case.
NEXT : Zero-Fill Number.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.