免责声明:我是编程新手!我确实看过 S.O.在发布之前找到这个问题的答案,但没有找到我需要的答案。
现在,我正在使用的 API 正在返回一个变量:'description'。 'description' 是一个动态的 250 个字符的字符串,带有标点符号。
我必须将字符串 chop 为 110 个字符,然后在其后插入省略号。这很简单 - 我一直在使用类似的东西:
description.slice(0,110) + "..."
但以上是有问题的,因为我无法预测我的字符串将被 chop 的字符。如果它在标点符号或空格处 chop ,结果看起来真的很傻:
我读过很多类似的咨询,开发人员想知道如何去掉字符串末尾的标点符号。但我可能需要删除几个标点符号,具体取决于随变量返回的标点符号或空格的数量。
谁能告诉我解决这个问题的最佳方法?如果我可以提供任何其他信息,请告诉我。
最佳答案
根据我的评论,我会稍微不同地处理它,以确保完整的话。
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 + '...';
}
关于Javascript:如何从字符串末尾删除标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388168/