Quickly remove HTML tags from a string using JavaScript with the following code snippets.
JavaScript
/**
* Remove HTML tags from a string
* @param {string} inputString - The string containing HTML tags
* @returns {string} - The string with HTML tags removed
*/
function stripHtmlTags(inputString) {
return inputString.replace(/<[^>]*>/g, '');
}
This function utilizes a regular expression (/<[^>]*>/g
) to match and replace all HTML tags in the input string with an empty string.
Usage
To strip HTML tags from a string in JavaScript, you can use the following function:
JavaScript
const stringWithHtml = '<p>This is <b>HTML</b> text.</p>';
const stringWithoutHtml = stripHtmlTags(stringWithHtml);
console.log(stringWithoutHtml);
// Output: "This is HTML text."
FAQs
Can this function handle nested HTML tags?
Yes, The regular expression used in the stripHtmlTags
function is designed to handle nested HTML tags. It will remove all tags, including nested ones.
Will this function remove content within script or style tags?
Yes, the function will remove content within script and style tags as well, treating them like any other HTML tags.
References
- MDN Web Docs: String.prototype.replace()
- Regular Expressions – MDN Web Docs: Regular Expressions