javascript截断字符串,不包括标点符号或空格

问题描述 投票:3回答:2

这是我尝试截断字符串

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

javascript slice
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

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))
© www.soinside.com 2019 - 2024. All rights reserved.