JavaScript截取字符串但不包括标点符号或空格。

3

这是我试图截断字符串的方法。

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...');```


为什么同一个结果需要使用 num > 3num <= 3 这两个不同的条件呢? - Kévin Bibollet
2个回答

2
你可以使用 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


谢谢, 请问我该如何为那种情况进行自定义。 'Hello world!'.truncate(2) ===> 'He... 'Hello'.truncate(5) ===> 'Hello' 'Hi!'.truncate(5) ===> 'Hi!' - irkoch
然后,创建一个条件语句,如果不是 !,则添加 ... - Yosvel Quintero

1

一种选择是构建一个正则表达式,匹配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))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接