gpt4 book ai didi

javascript - 如何将包含 HTML 标签的文本剪切到预期长度?

转载 作者:行者123 更新时间:2023-11-28 03:22:19 26 4
gpt4 key购买 nike

首先,我有一个字符串(文本有 245 个字符):

var string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."

然后我写一些像这样的html:

var stringHTML = "<p>Lorem Ipsum is simply dummy text of <a href='#print'>the printing</a> and typesetting industry. <b>Lorem Ipsum</b> has been the <i>industry's<i> standard dummy <span>text ever</span> since the 1500s, when <strong>an unknown</strong> printer took a galley of type and scrambled it to make a type specimen book</p>"

然后我需要将其削减到150个字符(150个字符将不包括html标签)

==> “Lorem Ipsum 只是打印和排版行业的虚拟文本。Lorem Ipsum 自 150 世纪以来一直是行业标准虚拟文本。”

但我需要结果是这样的:

var resultExpected = "<p>Lorem Ipsum is simply dummy text of <a href='#print'>the printing</a> and typesetting industry. <b>Lorem Ipsum</b> has been the <i>industry's<i> standard dummy <span>text ever</span> since the 150.</p>"

知道怎么做吗?如果是,请给我一些示例代码。

感谢您的支持。

最佳答案

我能够 trim 您的 stringHTML 的前 150 个字符字符串而不丢失任何 html 标签。

var stringHTML = "<p>Lorem Ipsum is simply dummy text of <a href='#print'>the printing</a> and typesetting industry. <b>Lorem Ipsum</b> has been the <i>industry's<i> standard dummy <span>text ever</span> since the 1500s, when <strong>an unknown</strong> printer took a galley of type and scrambled it to make a type specimen book</p>";
console.log(stringHTML.substring(0, 150));

如果您的意思是希望 150 个字符计数忽略 html 标签,那么您可以做的是逐个字符循环字符串并计算字符数,当达到 < 时char(或预设子字符串,如 <p ),您将停止计数,直到达到 >达到 150 后检查索引(原始字符串)并使用该索引使用 substring(0, index) .

关于javascript - 如何将包含 HTML 标签的文本剪切到预期长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com