In this article, you are going to learn how to truncate a string in Javascript. We are going to create a function that will accept two parameters. The first one will be the string itself, and the second will be the maximum length of string characters we are going to accept before we perform a truncate.
In the logic we are going to check if the length of the string is less or equal to the maximum length than we are not going to perform any truncate otherwise, we will truncate the string and include the trail dots to indicate the string has already been truncated.
Here is the Javascript code.
truncate = function(str, maxLength){ return (str.length <= maxLength) ? str : str.substring(0, maxLength) + '...'; }
Here is the example on how to use the above function script.
var sampleText = "This is a sample text."; var truncateText = truncate(sampleText, 10); console.log(truncateText);