简体   繁体   English

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

[英]Javascript: how to remove punctuation from the end of a string

Disclaimer: I'm new to programming! 免责声明:我是编程新手! I did look through SO to find the answer to this question before posting, but didn't find the answer I need. 在发布之前我确实通过SO查找了这个问题的答案,但没有找到我需要的答案。

Right now, the API I'm working with is returning a variable: 'description'. 现在,我正在使用的API返回一个变量:'description'。 'description' is a dynamic, 250-character string with punctuation. 'description'是带有标点符号的动态,250个字符的字符串。

I have to truncate the string to 110 characters and then insert an ellipsis after it. 我必须将字符串截断为110个字符,然后在其后插入省略号。 This is easy enough - I've been using something like: 这很容易 - 我一直在使用类似的东西:

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

But the above is problematic because I have no way of predicting what character my string will truncate on. 但上面的问题是有问题的,因为我无法预测我的字符串将截断的字符。 If it truncates on punctuation or a white space, the result looks really silly: 如果它在标点符号或空格上截断,结果看起来很傻:

在此输入图像描述

I've been reading a lot of similar inquiries where developers want to know how to take off one punctuating character at the end of a string. 我一直在阅读很多类似的查询,开发人员想要知道如何在字符串末尾删除一个标点符号。 But I might have to take off several punctuating characters, depending on how much punctuation or white space is returned with the variable. 但我可能不得不取消几个标点字符,具体取决于变量返回多少标点符号或空格。

Can anyone advise me on the best way to go about this? 谁能告诉我最好的方法呢? If I can provide any additional information, please let me know. 如果我可以提供任何其他信息,请告诉我。

Per my comment, I would approach it slightly differently, to assure whole words. 根据我的评论,我会略微区别对待,以确保整个单词。

 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 + '...'; } 

You could use the trim to remove the extra spaces at the end : 您可以使用修剪来删除末尾的额外空格:

var description = description.slice(0,110).trim(); //trim to remove spaces

Then add a condition to check if there's a dot at the end if yes add two others else add three punctuations : 然后添加一个条件来检查最后是否有一个点如果是,则添加另外两个其他添加三个标点符号:

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

Hope this helps. 希望这可以帮助。

 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); 

Snippet with . 片段与. and spaces at the end : 和最后的空格:

 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); 

I think this will work! 我认为这会奏效!

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, "") + '...';

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM