VueJs过滤器应该显示最后一个单词full



我使用了vue过滤器将文本限制为100个字符。我得到的输出是

Tat is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the indu ...

如果您看到最后一个单词indu ...,。我不想在单词和点之间有一个单词分解,相反,我希望它像完整的单词然后是点,如下所示:

Tat is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's ...

单词应该在100个字符后完成,然后需要添加...

下面是我使用的Vue过滤器,我如何才能以完整的单词结尾,然后用点代替最后一个单词的几个字符?

msg = "<p> Tat 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. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing</p>n" 
<h2 v-html="this.$options.filters.limitText(msg)" ></h2>
filters: {
limitText: function (val) {
if(val && (val.length > 100) {
return (val.substr(0, 100) + ' ...')
}
return val;
}
}

使用正则表达式,我提出了这个解决方案:

const msg = `Tat 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. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing`
console.log(msg.substr(0, 100).replace(/sS*$/, ''))

基本上,在提取100个第一个字符后,我使用正则表达式查找后面跟着非空格字符的最后一个空格,并删除这些字符。

1-获取第一个100个字符的

2-切片,直到下一个空格或文本末尾的索引。

const msg = `Tat 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. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing`
const LAST_INDEX = 99
let msgShort = msg.substring(0,LAST_INDEX)+msg.slice(LAST_INDEX,msg.indexOf(' ',LAST_INDEX))+'...'
console.log(msgShort)

  • 不建议使用substr。请改用substring

最新更新