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.">&nbsp<a href="javascript:void(0)">[...]</a></span>'

var truncated = _.truncate(string, {length: 150, separator: /,? +/, omission: omission});

console.log(truncated)
    
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>


输出仅包含省略变量,而不包含字符串的前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.">&nbsp<a href="javascript:void(0)">[...]</a></span>'

最佳答案

首先要保持简单。

您正在尝试使一件事(省略指示器)做两件事。

  • 表示省略
  • 成为可点击的元素

  • 为了简化起见,首先隐藏省略指示器,然后在str.length超过150个字符时添加clickable元素。
    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 +'">&nbsp<a href="javascript:void(0)">[...]</a></span>';
    }
    
    var truncated = _.truncate(str, {length: stringLimit, separator: /,? +/, omission: ''});
    
    console.log(truncated + popoverToggle);
    document.write(truncated + popoverToggle);
    

    看到我的Codepen

    关于javascript - lodash- chop 函数返回错误结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49820488/

    10-13 00:18