Lodash _.truncate函数使用以下代码段返回错误的结果,其中omission
参数中使用了长HTML字符串。
我想知道是否存在我没有正确执行的操作,或者问题是否存在于库本身中。
var string = "In publishing and graphic design, lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content. Replacing the actual content with placeholder text allows designers to design the form of the content before the content itself has been produced."
var omission = '<span data-toggle="popover" data-placement="top" data-trigger="hover" data-html="true" data-content="In publishing and graphic design, lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content. Replacing the actual content with placeholder text allows designers to design the form of the content before the content itself has been produced."> <a href="javascript:void(0)">[...]</a></span>'
var truncated = _.truncate(string, {length: 150, separator: /,? +/, omission: omission});
console.log(truncated)
&#13;
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
&#13;
输出仅包含省略变量,而不包含字符串
的前150个字符预期输出:
'In publishing and graphic design, lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on<span data-toggle="popover" data-placement="top" data-trigger="hover" data-html="true" data-content="In publishing and graphic design, lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content. Replacing the actual content with placeholder text allows designers to design the form of the content before the content itself has been produced."> <a href="javascript:void(0)">[...]</a></span>'
答案 0 :(得分:2)
我不知道说这是图书馆的问题是否公平。据我所知,omission
部分返回一个字符串,所以如果你有一个100个字符长的字符串,你想截断50,但遗漏字符串是200,那么它有点失败的目的,即使你想要做的是用HTML元素替换它。
查看此处_.truncate
的{{1}}源代码,您会注意到如果options.length
小于options.omission
的长度,则会返回{{ 1}}。
我通过将options.omission
的值更改为更短的内容进行了测试,并确实返回了https://github.com/lodash/lodash/blob/4.17.5/lodash.js#L15079。
如果我理解你要做的是什么,我想知道首先截断字符串是否有意义,然后在那之后追加popover HTML,而不是使用lodash来做。
答案 1 :(得分:2)
第一条规则是保持简单。
你正试图让一件事(遗漏指标)做两件事。
为了简单起见,首先隐藏遗漏指示符,然后在str.length
超过150个字符时添加可点击元素。
var stringLimit = 150;
var str = "In publishing and graphic design, lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document without relying on meaningful content. Replacing the actual content with placeholder text allows designers to design the form of the content before the content itself has been produced."
var popoverToggle = '';
if (str.length > stringLimit) {
popoverToggle = '<span data-toggle="popover" data-placement="top" data-trigger="hover" data-html="true" data-content="'+ str +'"> <a href="javascript:void(0)">[...]</a></span>';
}
var truncated = _.truncate(str, {length: stringLimit, separator: /,? +/, omission: ''});
console.log(truncated + popoverToggle);
document.write(truncated + popoverToggle);
查看我的Codepen