w3resource

JavaScript: Truncate a string if it is longer than the specified number of characters

JavaScript String: Exercise-16 with Solution

Write a JavaScript function to truncate a string if it is longer than the specified number of characters. Truncated strings will end with a translatable ellipsis sequence ("…") (by default) or specified characters.

Test Data:
console.log(text_truncate('We are doing JS string exercises.'))
console.log(text_truncate('We are doing JS string exercises.',19))
console.log(text_truncate('We are doing JS string exercises.',15,'!!'))
"We are doing JS string exercises."
"We are doing JS ..."
"We are doing !!"

Sample Solution:

JavaScript Code:

// Define a function named text_truncate that takes three parameters: str (the input string), length (the maximum length of the output string), and ending (the optional ending to append if the string is truncated)
text_truncate = function(str, length, ending) {
    // If the length parameter is not provided, set it to 100 characters
    if (length == null) {
      length = 100;
    }
    // If the ending parameter is not provided, set it to '...'
    if (ending == null) {
      ending = '...';
    }
    // Check if the length of the input string exceeds the specified length
    if (str.length > length) {
      // If yes, truncate the string to length - ending.length characters and append the ending
      return str.substring(0, length - ending.length) + ending;
    } else {
      // If no, return the original string
      return str;
    }
  };
// Test the function with different input strings and output the results to the console
console.log(text_truncate('We are doing JS string exercises.'))
console.log(text_truncate('We are doing JS string exercises.',19))
console.log(text_truncate('We are doing JS string exercises.',15,'!!'))

Output:

We are doing JS string exercises.
We are doing JS ...
We are doing !!

Explanation:

In the exercise above,

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-string-exercise-16.php