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

853
December 30, 2016, at 3:14 PM

Disclaimer: I'm new to programming! I did look through S.O. to find the answer to this question before posting, but didn't find the answer I need.

Right now, the API I'm working with is returning a variable: 'description'. 'description' is a dynamic, 250-character string with punctuation.

I have to truncate the string to 110 characters and then insert an ellipsis after it. 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.

Answer 1

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

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

Answer 3

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

Answer 4

The long and short of it is you'll have to use slice along with either .contains or .indexOf and test for each type of punctuation, but only at the end of the string

Rent Charter Buses Company
READ ALSO
Is it possible to specify a custom width for CSS media rules to use in order to force a desktop mode?

Is it possible to specify a custom width for CSS media rules to use in order to force a desktop mode?

I want to give my mobile users a desktop mode, but I'm really not interested in making a non-responsive CSS version for every css file i have, so i wonder if it is possible without

534
To implement realtime search box [on hold]

To implement realtime search box [on hold]

I am developing an Android app like FlipkartHow can I implement a search box in the toolbar to search products as auto complete text? Data should not stored in an internal array

731
How to make java class that it contains some Persian entries to jar file

How to make java class that it contains some Persian entries to jar file

I have just a class I want to become the JAR file And because it contains some Persian entries After converting to a JAR file is written in Persian Is troubled And for this reason Farsi entries must be defined in file string

399
can you recomend me for good program to build mobile apps? [on hold]

can you recomend me for good program to build mobile apps? [on hold]

can you recomend me for good program to build mobile apps? I downloaded the android studio (https://developerandroid

315