这是我尝试截断字符串
String.prototype.truncate = function (num) {
var str = this;
if (str.length > num && num > 3 ) {
console.log(str.length);
return str.slice(0, num) + "...";
} else if (str.length > num && num <= 3) {
console.log('ok');
return str.slice(0, num) + "...";
} else {
console.log(str.length);
return str;
}
}
请任何身体,知道如何解决它,谢谢
'Hello world!'.truncate(2) ====> 'He...'
'Hello world!'.truncate(6) ====> 'Hello...');
'Hello, world!'.truncate(6)====> 'Hello...');```
您可以使用String.prototype.trim()删除多余的空格和String.prototype.replace()来替换最后一个字符,如果,
由''
最后添加...
码:
String.prototype.truncate = function(num) {
return `${this.slice(0, num).trim().replace(/\,$/, '')}...`;
}
console.log('Hello world!'.truncate(2)); // ====> 'He...'
console.log('Hello world!'.truncate(6)); // ====> 'Hello...'
console.log('Hello, world!'.truncate(6)); // ====> 'Hello...'
根据你的评论:
String.prototype.truncate = function(num) {
const str = this.slice(0, num).trim().replace(/\,$/, '');
return str[str.length - 1] !== '!' ? `${str}...`: str;
}
console.log('Hello world!'.truncate(2)); // ====> 'He...'
console.log('Hello world!'.truncate(6)); // ====> 'Hello...'
console.log('Hello, world!'.truncate(6)); // ====> 'Hello...'
console.log('Hi!'.truncate(5)); // ====> 'Hi!' <---- On the comments
一种选择是构造一个匹配num - 1
单词字符的正则表达式,可能前面有任意数量的非单词字符(如空格和标点符号):
String.prototype.truncate = function (num) {
const pattern = new RegExp(`(?:\\W*\\w){${num - 1}}`);
return this.match(pattern)[0] + '...';
}
console.log('Hello, world!'.truncate(6))