JavaScript:如何从字符串末尾删除标点符号

4

免责声明:我是编程新手!在发帖之前,我确实查阅了S.O.以找到这个问题的答案,但没有找到我需要的答案。

目前,我正在使用的API返回一个变量:“description”。 “description”是一个动态的、250个字符带标点符号的字符串。

我必须将字符串截断为110个字符,然后在其后插入省略号。这很容易 - 我一直在使用类似以下的代码:

description.slice(0,110) + "..."

但是上述方法存在问题,因为我无法预测我的字符串将在哪个字符处截断。如果它在标点符号或空格上截断,结果看起来非常愚蠢:

enter image description here

我已经阅读了很多类似的询问,开发人员想知道如何去掉字符串末尾的一个标点符号。但是根据变量返回的标点符号或空格数量不同,我可能需要去掉多个标点符号。
请问有人能够建议我最好的方法吗?如果我可以提供任何额外信息,请告诉我。

1
这里有一个仅使用CSS的替代方案(尽管我认为它不允许您控制截断发生的字符):http://caniuse.com/#feat=text-overflow - jtbandes
检查切片描述,使用charAt(str.length-1),添加条件...如果末尾有点,则添加两个点,如果没有-> 3...之类的东西... - sinisake
1
我建议采用不同的方法:基于单词进行分割,然后将长度小于110个字符的单词拼接起来。这样,您可以确保只获取整个单词,而不是像**long sle...**这样的奇怪东西。 - random_user_name
3个回答

2
根据我的评论,我会稍微不同的方式来处理,以确保整个单词。

var string = "This is a sentence. A long sentence that should be broken up so it's not too long.  Got it?  Good.  How long. does it get?";

var excerpt = createExcerpt(string);
console.log(excerpt);

// Function to parse a sentence into an excerpt, based on whole words
function createExcerpt(string, maxLength) {
  // Set a default value of maxLength of 110
  maxLength = maxLength | 110;
  // If it's not too long, don't do anything
  if (string.length <= maxLength) {
    return string;
  }
  
  // Break it up into words
  var words = string.split(' ');
  var excerpt = '';
  // Loop over the words in order
  words.forEach(function(word) {
    // Build a test string to see if it's too long
    test = excerpt + ' ' + word;
    // If it's too long, then break out of the loop
    if (test.length > maxLength) {
      return false;
    }

    // Otherwise, set the excerpt to the new test string
    excerpt = test;
  });

  // Remove any extra spaces / dots at the end of the excerpt
  excerpt =  excerpt.replace(/[\s|\.]+$/i, '');
  // Return the excerpt with ellipses
  return excerpt + '...';
}


0
你可以使用 trim 函数来移除末尾的额外空格:
var description = description.slice(0,110).trim(); //trim to remove spaces

然后添加一个条件来检查末尾是否有句点,如果有,则添加两个其他标点符号,否则添加三个标点符号:

if (description[description.length-1] === ".")
    description += '..';
else
    description += '...';

希望这能帮到你。

var description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

description = description.slice(0,110).trim();

if (description[description.length-1] === ".")
    description += '..';
else
    description += '...';

console.log(description);

.和空格结尾的代码片段:

var description = "Lorem ipsum dolor sit amet,consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore.  magna aliqua.";

description = description.slice(0,110).trim();

if (description[description.length-1] === ".")
    description += '..';
else
    description += '...';

console.log(description);


0

我认为这会起作用!

function truncateWholeWords (text, maxLength) {
    maxLength = maxLength || 110; 
    var length = 0;

    return text.split(' ').filter(function (word) {
        length += (word.length+1);
        return length <= maxLength;
    }).join(' ').replace(/([.,\/#!$%\^&\*;:{}=\-_`~()\]\[])+$/g, "") + '...';

}

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