我正在使用substring
裁剪我的文本:
const trimmedLead = lead.substring(0, 118) + '...'
但现在,它也打破了文字。如何在Javascript中实现同样的功能,但又不会破坏单词?
发布于 2020-10-13 02:31:19
你可以在你喜欢的地方拆分字符串,然后你可以检查第一部分是否以字符结束,第二部分是否以字符开始。如果这两个都是真的,你就拆分一个单词。如果拆分单词,请使用replace切回到单词边界的末尾。
function trimDownToWord(string, maxLength) {
if (string <= maxLength) {
return string;
}
let first = string.substr(0, maxLength);
const second = string.substr(maxLength);
if (/\w$/.test(first) && /^\w/.test(second)) {
first = first.replace(/\b[^\w]*\w+$/, '');
}
return first.trim() + '...';
}
const lead = `This is multiple words, many fun words to read!`
// Without word trimming:
const trimmedAtLength = lead.substring(0, 25) + '...';
console.log(trimmedAtLength);
// With word trimming:
const trimmedByWords = trimDownToWord(lead, 26);
console.log(trimmedByWords);
https://stackoverflow.com/questions/64323199
复制相似问题