{"id":17109949,"url":"https://github.com/oe/truncate-html","last_synced_at":"2025-04-12T18:48:51.211Z","repository":{"id":35884783,"uuid":"46834373","full_name":"oe/truncate-html","owner":"oe","description":"truncate html and keep tag in safe","archived":false,"fork":false,"pushed_at":"2025-03-18T15:03:20.000Z","size":1233,"stargazers_count":62,"open_issues_count":0,"forks_count":12,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-12T11:14:46.889Z","etag":null,"topics":["html","truncate","truncate-html","truncate-words"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/oe.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"ko_fi":"esaiya","github":"oe"}},"created_at":"2015-11-25T03:13:48.000Z","updated_at":"2025-03-18T15:03:34.000Z","dependencies_parsed_at":"2025-02-05T04:35:28.167Z","dependency_job_id":null,"html_url":"https://github.com/oe/truncate-html","commit_stats":{"total_commits":96,"total_committers":12,"mean_commits":8.0,"dds":0.6875,"last_synced_commit":"f2b2359e49c2fd14b31d209866c163ea08aaa328"},"previous_names":["evecalm/truncate-html"],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oe%2Ftruncate-html","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oe%2Ftruncate-html/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oe%2Ftruncate-html/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/oe%2Ftruncate-html/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/oe","download_url":"https://codeload.github.com/oe/truncate-html/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248618215,"owners_count":21134199,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["html","truncate","truncate-html","truncate-words"],"created_at":"2024-10-14T16:24:55.328Z","updated_at":"2025-04-12T18:48:51.182Z","avatar_url":"https://github.com/oe.png","language":"TypeScript","funding_links":["https://ko-fi.com/esaiya","https://github.com/sponsors/oe"],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003etruncate-html\u003c/h1\u003e\n\n\u003ch5 align=\"center\"\u003e Truncate html string(even contains emoji chars) and keep tags in safe. You can custom ellipsis sign, ignore unwanted elements and truncate html by words. \u003c/h5\u003e\n\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"https://github.com/oe/truncate-html/actions/workflows/main.yml\"\u003e\n    \u003cimg src=\"https://github.com/oe/truncate-html/actions/workflows/main.yml/badge.svg\" alt=\"Github Actions\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"#readme\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/%3C%2F%3E-typescript-blue\" alt=\"code with typescript\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"#readme\"\u003e\n    \u003cimg src=\"https://badge.fury.io/js/truncate-html.svg\" alt=\"npm version\"\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.com/package/truncate-html\"\u003e\n    \u003cimg src=\"https://img.shields.io/npm/dm/truncate-html.svg\" alt=\"npm downloads\"\u003e\n  \u003c/a\u003e\n\u003c/div\u003e\n\n\u003cbr\u003e\n\n**Notice** This is a node module depends on [cheerio](https://github.com/cheeriojs/cheerio) _can only run on nodejs_. If you need a browser version, you may consider [truncate](https://github.com/pathable/truncate) or [nodejs-html-truncate](https://github.com/huang47/nodejs-html-truncate).\n\n```javascript\nconst truncate = require('truncate-html')\ntruncate('\u003cp\u003e\u003cimg src=\"xxx.jpg\"\u003eHello from earth!\u003c/p\u003e', 2, { byWords: true })\n// =\u003e \u003cp\u003e\u003cimg src=\"xxx.jpg\"\u003eHello from ...\u003c/p\u003e\n```\n\n## Installation\n\n`npm install truncate-html` \u003cbr\u003e\nor \u003cbr\u003e\n`yarn add truncate-html`\n\n## Try it online\n\nClick **\u003chttps://npm.runkit.com/truncate-html\u003e** to try.\n\n## API\n\n```ts\n/**\n * custom node strategy, default to Cheerio\u003cAnyNode\u003e\n * * 'remove' to remove the node\n * * 'keep' to keep the node(and anything inside it) anyway, and won't be counted as there is no text content in it\n * * Cheerio\u003cAnyNode\u003e truncate the returned node\n * * undefined or any falsy value to truncate original node\n */\ntype ICustomNodeStrategy = (node: Cheerio\u003cAnyNode\u003e) =\u003e 'remove' | 'keep' | Cheerio\u003cAnyNode\u003e | undefined\n\n/**\n * truncate-html full options object\n */\ninterface IFullOptions {\n  /**\n   * remove all tags, default false\n   */\n  stripTags: boolean\n  /**\n   * ellipsis sign, default '...'\n   */\n  ellipsis: string\n  /**\n   * decode html entities(e.g. convert `\u0026amp;` to `\u0026`) before counting length, default false\n   */\n  decodeEntities: boolean\n  /**\n   * elements' selector you want ignore\n   */\n  excludes: string | string[]\n  /**\n   * custom node strategy, default to Cheerio\u003cAnyNode\u003e\n   * * 'remove' to remove the node\n   * * 'keep' to keep the node(and anything inside it) anyway, and won't be counted as there is no text content in it\n   * * Cheerio\u003cAnyNode\u003e truncate the returned node\n   * * undefined or any falsy value to truncate original node\n   */\n  customNodeStrategy: ICustomNodeStrategy\n  /**\n   * how many letters(words if `byWords` is true) you want reserve\n   */\n  length: number\n  /**\n   * if true, length means how many words to reserve\n   */\n  byWords: boolean\n  /**\n   * how to deal with when truncate in the middle of a word\n   *  1. by default, just cut at that position.\n   *  2. set it to true, with max exceed 10 letters can exceed to reserver the last word\n   *  3. set it to a positive number decide how many letters can exceed to reserve the last word\n   *  4. set it to negative number to remove the last word if cut in the middle.\n   */\n  reserveLastWord: boolean | number\n  /**\n   * if reserveLastWord set to negative number, and there is only one word in the html string,  when trimTheOnlyWord set to true, the extra letters will be sliced if word's length longer than `length`.\n   * see issue #23 for more details\n   */\n  trimTheOnlyWord: boolean\n  /**\n   * keep whitespaces, by default continuous paces will\n   *  be replaced with one space, set it true to keep them\n   */\n  keepWhitespaces: boolean\n}\n\n/**\n * options interface for function\n */\ntype IOptions = Partial\u003cIFullOptions\u003e\n\nfunction truncate(html: string | CheerioAPI, length?: number | IOptions,  truncateOptions?: IOptions): string\n// and truncate.setup to change default options\ntruncate.setup(options: IOptions): void\n```\n\n### Default options\n\n```js\n{\n  stripTags: false,\n  ellipsis: '...',\n  decodeEntities: false,\n  excludes: '',\n  byWords: false,\n  reserveLastWord: false,\n  trimTheOnlyWord: false,\n  keepWhitespaces: false\n}\n```\n\nYou can change default options by using `truncate.setup`\n\ne.g.\n\n```ts\ntruncate.setup({ stripTags: true, length: 10 })\ntruncate('\u003cp\u003e\u003cimg src=\"xxx.jpg\"\u003eHello from earth!\u003c/p\u003e')\n// =\u003e Hello from\n```\n\nor use existing [cheerio instance](https://github.com/cheeriojs/cheerio#loading)\n\n```ts\nimport * as cheerio from 'cheerio'\ntruncate.setup({ stripTags: true, length: 10 })\n// truncate option `decodeEntities` will not work\n//    you should config it in cheerio options by yourself\nconst $ = cheerio.load('\u003cp\u003e\u003cimg src=\"xxx.jpg\"\u003eHello from earth!\u003c/p\u003e', {\n  /** set decodeEntities if you need it */\n  decodeEntities: true\n  /* any cheerio instance options*/\n}, false) // third parameter is for `isDocument` option, set to false to get rid of extra wrappers, see cheerio's doc for details\ntruncate($)\n// =\u003e Hello from\n```\n\n\n## Notice\n\n### Typescript support\n\nThis lib is written with typescript and has a type definition file along with it. ~~You may need to update your `tsconfig.json` by adding `\"esModuleInterop\": true` to the `compilerOptions` if you encounter some typing errors, see [#19](https://github.com/oe/truncate-html/issues/19).~~\n\n```ts\nimport truncate, { type IOptions } from 'truncate-html'\n\n\nconst html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003e\u003ci\u003eitalic\u003cb\u003ebold\u003c/b\u003e\u003c/i\u003eThis is a string\u003c/p\u003e for test.'\n\nconst options: IOptions = {\n  length: 10,\n  byWords: true\n}\n\ntruncate(html, options)\n// =\u003e \u003cp\u003e\u003cimg src=\"abc.png\"\u003e\u003ci\u003eitalic\u003cb\u003ebold...\u003c/b\u003e\u003c/i\u003e\u003c/p\u003e\n```\n\n### custom node truncate strategy\nIn complex html string, you may want to keep some special elements and truncate the others. You can use `customNodeStrategy` to achieve this:\n* return `'remove'` to remove the node\n* `keep` to keep the node(and anything inside it) anyway, and won't be counted as there is no text content in it\n* `Cheerio\u003cAnyNode\u003e` to truncate the returned node, or any falsy value to truncate the original node.\n\n```ts\nimport truncate, { type IOptions, type ICustomNodeStrategy } from 'truncate-html'\n\n// argument node is a cheerio instance\nconst customNodeStrategy: ICustomNodeStrategy = node =\u003e {\n  // remove img tag\n  if (node.is('img')) {\n    return 'remove'\n  }\n  // keep italic tag and its children\n  if (node.is('i')) {\n    return 'keep'\n  }\n  // truncate summary tag that inside details tag instead of details tag\n  if (node.is('details')) {\n    return node.find('summary')\n  }\n}\n\nconst html = '\u003cdiv\u003e\u003cimg src=\"abc.png\"\u003e\u003ci\u003eitalic\u003cb\u003ebold\u003c/b\u003e\u003c/i\u003e\u003cdetails\u003e\u003csummary\u003eClick me\u003c/summary\u003e\u003cp\u003eSome details\u003c/p\u003e\u003c/details\u003eThis is a string\u003c/div\u003e for test.'\n\nconst options: IOptions = {\n  length: 10,\n  customNodeStrategy\n}\n\ntruncate(html, options)\n// =\u003e \u003cdiv\u003e\u003ci\u003eitalic\u003cb\u003ebold\u003c/b\u003e\u003c/i\u003e\u003cdetails\u003e\u003csummary\u003eClick me\u003c/summary\u003e\u003cp\u003eSome details\u003c/p\u003e\u003c/details\u003eTh...\u003c/div\u003e\n\n\n```\n\n### About final string length\n\nIf 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 string length will be `options.length` + `options.ellipsis`. And if you set `reserveLastWord` to true or none zero number or using `customNodeStrategy`, the final string will be various.\n\n### About html comments\n\nAll html comments `\u003c!-- xxx --\u003e` will be removed\n\n### About dealing with none alphabetic languages\n\nWhen dealing with none alphabetic languages, such as Chinese/Japanese/Korean, they don't separate words with whitespaces, so options `byWords` and `reserveLastWord` should only works well with alphabetic languages.\n\nAnd the only dependency of this project `cheerio` has an issue when dealing with none alphabetic languages, see [Known Issues](#known-issues) for details.\n\n### Using existing cheerio instance\n\nIf you want to use existing cheerio instance, truncate option `decodeEntities` will not work, you should set it in your own cheerio instance:\n\n```js\nvar html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e for test.'\nconst $ = cheerio.load(`${html}`, {\n  decodeEntities: true\n  /** other cheerio options */\n}, false) // third parameter is for `isDocument` option, set to false to get rid of extra wrappers, see cheerio's doc for details\ntruncate($, 10)\n\n```\n\n## Examples\n\n```javascript\nvar truncate = require('truncate-html')\n\n// truncate html\nvar html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e for test.'\ntruncate(html, 10)\n// returns: \u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a ...\u003c/p\u003e\n\n// truncate string with emojis\nvar string = '\u003cp\u003epoo 💩💩💩💩💩\u003cp\u003e'\ntruncate(string, 6)\n// returns: \u003cp\u003epoo 💩💩...\u003c/p\u003e\n\n// with options, remove all tags\nvar html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e for test.'\ntruncate(html, 10, { stripTags: true })\n// returns: This is a ...\n\n// with options, truncate by words.\n//  if you try to truncate none alphabet language(like CJK)\n//      it will not act as you wish\nvar html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e for test.'\ntruncate(html, 3, { byWords: true })\n// returns: \u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a ...\u003c/p\u003e\n\n// with options, keep whitespaces\nvar html = '\u003cp\u003e         \u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e for test.'\ntruncate(html, 10, { keepWhitespaces: true })\n// returns: \u003cp\u003e         \u003cimg src=\"abc.png\"\u003eThis is a ...\u003c/p\u003e\n\n// combine length and options\nvar html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e for test.'\ntruncate(html, {\n  length: 10,\n  stripTags: true\n})\n// returns: This is a ...\n\n// custom ellipsis sign\nvar html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e for test.'\ntruncate(html, {\n  length: 10,\n  ellipsis: '~'\n})\n// returns: \u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a ~\u003c/p\u003e\n\n// exclude some special elements(by selector), they will be removed before counting content's length\nvar html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e for test.'\ntruncate(html, {\n  length: 10,\n  ellipsis: '~',\n  excludes: 'img'\n})\n// returns: \u003cp\u003eThis is a ~\u003c/p\u003e\n\n// exclude more than one category elements\nvar html =\n  '\u003cp\u003e\u003cimg src=\"abc.png\"\u003eThis is a string\u003c/p\u003e\u003cdiv class=\"something-unwanted\"\u003e unwanted string inserted ( ´•̥̥̥ω•̥̥̥` ）\u003c/div\u003e for test.'\ntruncate(html, {\n  length: 20,\n  stripTags: true,\n  ellipsis: '~',\n  excludes: ['img', '.something-unwanted']\n})\n// returns: This is a string for~\n\n// handing encoded characters\nvar html = '\u003cp\u003e\u0026nbsp;test for \u0026lt;p\u0026gt; encoded string\u003c/p\u003e'\ntruncate(html, {\n  length: 20,\n  decodeEntities: true\n})\n// returns: \u003cp\u003e test for \u0026lt;p\u0026gt; encode...\u003c/p\u003e\n\n// when set decodeEntities false\nvar html = '\u003cp\u003e\u0026nbsp;test for \u0026lt;p\u0026gt; encoded string\u003c/p\u003e'\ntruncate(html, {\n  length: 20,\n  decodeEntities: false // this is the default value\n})\n// returns: \u003cp\u003e\u0026nbsp;test for \u0026lt;p...\u003c/p\u003e\n\n// and there may be a surprise by setting `decodeEntities` to true  when handing CJK characters\nvar html = '\u003cp\u003e\u0026nbsp;test for \u0026lt;p\u0026gt; 中文 string\u003c/p\u003e'\ntruncate(html, {\n  length: 20,\n  decodeEntities: true\n})\n// returns: \u003cp\u003e test for \u0026lt;p\u0026gt; \u0026#x4E2D;\u0026#x6587; str...\u003c/p\u003e\n// to fix this, see below for instructions\n\n\n// custom node strategy to keep some special elements\nvar html = '\u003cp\u003e\u003cimg src=\"abc.png\"\u003e\u003ci\u003eitalic\u003cb\u003ebold\u003c/b\u003e\u003c/i\u003eThis is a string\u003c/p\u003e for test.'\ntruncate(html, {\n  length: 10,\n  customNodeStrategy: node =\u003e {\n    if (node.is('img')) {\n      return 'remove'\n    }\n    if (node.is('i')) {\n      return 'keep'\n    }\n  }\n})\n// returns: \u003cp\u003e\u003ci\u003eitalic\u003cb\u003ebold\u003c/b\u003e\u003c/i\u003eThis is a ...\u003c/p\u003e\n\n// custom node strategy to truncate summary instead of original node\nvar html = '\u003cdiv\u003e\u003cdetails\u003e\u003csummary\u003eClick me\u003c/summary\u003e\u003cp\u003eSome details\u003c/p\u003e\u003c/details\u003eother things\u003c/div\u003e'\ntruncate(html, {\n  length: 10,\n  customNodeStrategy: node =\u003e {\n    if (node.is('details')) {\n      return node.find('summary')\n    }\n  }\n})\n// returns: \u003cdiv\u003e\u003cdetails\u003e\u003csummary\u003eClick me\u003c/summary\u003e\u003cp\u003eSome details\u003c/p\u003e\u003c/details\u003eot...\u003c/div\u003e\n```\n\nfor More usages, check [truncate.spec.ts](./test/truncate.spec.ts)\n\n## Credits\n\nThanks to:\n\n- [@calebeno](https://github.com/calebeno) es6 support and unit tests\n- [@aaditya-thakkar](https://github.com/aaditya-thakkar) emoji truncating support\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foe%2Ftruncate-html","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Foe%2Ftruncate-html","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Foe%2Ftruncate-html/lists"}