javascript截断字符串而不包含标点或空格
这是我截断字符串的尝试javascript截断字符串而不包含标点或空格,javascript,slice,Javascript,Slice,这是我截断字符串的尝试 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 &&am
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;
}
}
一个选项是构造一个正则表达式,该正则表达式匹配
num-1
单词字符,可能前面有任意数量的非单词字符(如空格和标点符号):
String.prototype.truncate=函数(num){
constpattern=newregexp(`(?:\\W*\\W){${num-1}}`);
返回此.match(模式)[0]+'…';
}
console.log('Hello,world!'.truncate(6))
如果,
用'
替换最后一个字符,最后添加…
代码:
String.prototype.truncate=函数(num){
返回“${this.slice(0,num).trim().replace(/\,$/,'')}…”;
}
console.log('Hello world!'.truncate(2));//=>'他……”
console.log('Hello world!'.truncate(6));//=>'你好…'
console.log('Hello,world!'.truncate(6));//=>'您好…“
为什么使用num>3
和num有两种不同的情况谢谢,请问我如何为这种情况自定义此项。”世界你好。截断(2)==>“他…”您好。截断(5)==>“您好”“您好!”。截断(5)==>“嗨!”然后,如果与不同,则设置一个条件来添加…
代码>
'Hello world!'.truncate(2) ====> 'He...'
'Hello world!'.truncate(6) ====> 'Hello...');
'Hello, world!'.truncate(6)====> 'Hello...');```