What is string-strip-html?
The string-strip-html npm package is used to remove HTML tags from strings. It is useful for sanitizing user input, cleaning up text for display, and ensuring that text data is free from HTML elements.
What are string-strip-html's main functionalities?
Basic HTML Stripping
This feature allows you to remove HTML tags from a string, leaving only the text content. The example demonstrates stripping HTML tags from a simple string.
const { stripHtml } = require('string-strip-html');
const result = stripHtml('<p>Hello <strong>World</strong>!</p>');
console.log(result.result); // 'Hello World!'
Handling Self-Closing Tags
This feature handles self-closing tags, ensuring that they are removed from the string. The example shows how an image tag is stripped from the input string.
const { stripHtml } = require('string-strip-html');
const result = stripHtml('<img src="image.jpg" alt="Image" />');
console.log(result.result); // ''
Removing Attributes
This feature removes HTML tags along with their attributes, leaving only the text content. The example demonstrates stripping an anchor tag with an href attribute.
const { stripHtml } = require('string-strip-html');
const result = stripHtml('<a href="https://example.com">Link</a>');
console.log(result.result); // 'Link'
Other packages similar to string-strip-html
sanitize-html
The sanitize-html package allows for more granular control over HTML sanitization, including the ability to allow certain tags and attributes while removing others. It is more configurable compared to string-strip-html.
html-to-text
The html-to-text package converts HTML content to plain text while preserving some formatting, such as line breaks and lists. It is useful for converting HTML emails or web pages to readable text format.
he
The he package is used for encoding and decoding HTML entities. While it does not strip HTML tags, it is useful for handling HTML entities within text content.
string-strip-html
Strip HTML tags from strings. No parser, accepts mixed sources.
Install
This package is pure ESM. If you're not ready yet, install an older version of this program, 8.5.0 (npm i string-strip-html@8.5.0
).
npm i string-strip-html
Quick Take
import { strict as assert } from "assert";
import { stripHtml } from "string-strip-html";
assert.equal(
stripHtml("Some text <b>and</b> text.").result,
"Some text and text.",
);
assert.equal(stripHtml("aaa<div>bbb</div>ccc").result, "aaa bbb ccc");
assert.equal(
stripHtml("a <pre><code>void a;</code></pre> b", {
stripTogetherWithTheirContents: [
"script",
"style",
"xml",
"pre",
],
}).result,
"a b",
);
assert.equal(stripHtml("a < b and c > d").result, "a < b and c > d");
Documentation
Please visit codsen.com for a full description of the API. Also, try the GUI playground.
Contributing
To report bugs or request features or assistance, raise an issue on GitHub.
Licence
MIT License.
Copyright © 2010-2024 Roy Revelt and other contributors.