JSPM

  • Created
  • Published
  • Downloads 51660
  • Score
    100M100P100Q186519F
  • License MIT

truncate html and keep tags in safe

Package Exports

  • truncate-html

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (truncate-html) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Truncate-html

Truncate html string and keep tags in safe. You can custom ellipsis sign, ignore unwanted elements.

Notice This is a node module depends on cheerio can only run on nodejs. If you need a browser version, you may consider truncate or nodejs-html-truncate.

Method

truncate(html, [length], [options])

Available options

{
    length: Number, content length to truncate
    stripTags: Boolean, whether to remove tags
    ellipsis: String, custom ellipsis sign, set it to empty string to remove the ellipsis postfix
    excludes: String or Array, the selectors of the elements you want to ignore
}

Default options

truncate.defaultOptions = {
  stripTags: false,
  ellipsis: '...'
};

Install

npm install truncate-html

Usage

Notice Extra blank spaces in html content will be removed. If the html string content's length is shorter than options.length, then no ellipsis will be appended to the final html string. If longer, then the final html content's length will be options.length + options.ellipsis.

var truncate = require('truncate-html');

// truncate html
var html = '<p><img src="abc.png">This is a string</p> for test.';
truncate(html, 10);
// returns: <p><img src="abc.png">This is a ...</p>


// with options, remove all tags
var html = '<p><img src="abc.png">This is a string</p> for test.';
truncate(html, 10, {stripTags: true});
// returns: This is a ...



// combine length and options
var html = '<p><img src="abc.png">This is a string</p> for test.';
truncate(html, {
    length: 10,
    stripTags: true
});
// returns: This is a ...



// custom ellipsis sign
var html = '<p><img src="abc.png">This is a string</p> for test.';
truncate(html, {
    length: 10,
    ellipsis: '~'
});
// reutrns: <p><img src="abc.png">This is a ~</p>


// exclude some special elements(by selector), they will be removed before counting content's length
var html = '<p><img src="abc.png">This is a string</p> for test.';
truncate(html, {
    length: 10,
    ellipsis: '~',
    excludes: 'img'
});
// reutrns: <p>This is a ~</p>


// exclude more than one category elements
var html = '<p><img src="abc.png">This is a string</p><div class="something-unwanted"> unwanted string inserted ( ´•̥̥̥ω•̥̥̥` )</div> for test.';
truncate(html, {
    length: 20,
    stripTags: true,
    ellipsis: '~',
    excludes: ['img', '.something-unwanted']
});
// returns: This is a string for~