In this tutorial, let’s look at how to truncate a string in JavaScript. We’re going to be looking at using the ‘slice’, ‘splice’, ‘split’ and other pre-defined functions in JavaScript, as well as manual methods using the ‘for’ loop.
Let’s get to it then!
Check if the string is already within the limit
Before we truncate a string, we need to first check if our current string’s length is greater than the given limit, hence creating a need for truncation.
Let’s do that first. Look at the below lines of code:
const truncateString = (str, limit) => { if(str.length <= limit) { return str; } else { //truncate the string } }
As you can see, we’re first checking if the length of our string is lesser than or equal to the given limit. If it is, then we can return the string as it is since it does not require further truncation.
But if it is not, then we can truncate the string using the various methods we’ll be looking at next.
Truncate the string using the slice() method
One of the easiest ways to truncate a string is by using the ‘slice’ method. As the name implies, this method can be used to slice a portion of a string, based on the given starting and ending slice positions.
Now all we must do is slice the string from 0 (first position) till the length of the string, as shown below:
const truncateString = (str,length) => { str = str.slice(0,length) + "..."; return str; } console.log(truncateString("Hello there, how are you? This is a fine day, isn't it?",25)); //Hello there, how are you?...
If you noticed, we’ve given the values as 0 and length. Doesn’t that mean our program will slice length + 1 characters? No, it doesn’t.
Slice only slices until before the ending position, meaning, it doesn’t include the character at the ending position. So, 0 to length actually means slice from 0 to length-1, which will slice exactly ‘length’ number of characters from the start of the string, which is what we want.
Trim without cutting off words
So far, we’re trimming the string based on the number of characters that pertain to the ‘length’ value given during the function call.
This method doesn’t always work though. Look at the following example, for instance.
console.log(truncateString("Hello there, how are you? This is a fine day, isn't it?",22)); //Hello there, how are y...
In the above example, we’ve given the length as 22, and that’s cut off the word ‘y’. In such an instance, we could have gone without ‘y’ being included at all. We want our string trimmed to ‘length’, but we could do without a character or 2 if it doesn’t end up cutting words.
How can we rectify this mistake? To be on the safer side, we can make sure that our trimmed string always contains a trailing space (last character is a space), indicating that a full word comes next, and nothing was cut off.
This might cut off more characters than we want, but if you don’t like half-words in your trimmed string, then this is a good way to go about removing them.
const truncateString = (str,length) => { str = str.slice(0,length) + "..."; let index = 0; for(let i = 0; i < str.length; i++) { if(str[i] === ' ') { index = i; } } if(index + 1 < str.length) { str = str.slice(0,index); } return str; } console.log(truncateString("Hello there, how are you? This is a fine day, isn't it?",22)); //Hello there, how are...
As you can see, the trailing space was also removed. If you want to include the space, you can truncate from 0 to index+1.
Using the substring() method
So far, we’ve been using the ‘slice’ method, but we can replace that with the ‘substring’ method and arrive at the same result.
str = str.substring(0,length) + "...";
Use the split and join methods to specify string limit
The split method, as you know, can be used to split a string into an array based on the given split condition.
For example, if you give a single space as the split condition, the ‘split’ method will split at every word and place each as a separate array element.
Did you know that this method also comes with a second argument where you can specify the length of the split, effectively truncating the array being formed?
That’s correct. If you make the length argument you send in your function call as the second argument of the ‘split’ method, while the first argument is an empty string to ensure that every character takes up its own array element, then you end up with an array of ‘length’ elements.
Now, join these elements back into a string with yet another empty string as the join condition, to make sure that every character is fused back as it was before.
Voila, you now have ‘length’ number of characters in your string, just as you wanted, and it took just a single line of code. You’ve truncated your string using just the ‘split’ and ‘join’ methods now.
str = str.split('',length).join('') + "...";
Truncate to a certain number of words using split, join and slice
Alternatively, you can just split based on an empty string, using the Array slice method on the split array to make sure only 0 to length-1 elements remain, and join them back, as shown below:
str = str.split('').slice(0,length).join('');
Using the splice method instead
Instead of the ‘slice’ method, you can use the ‘splice’ method as well. This method directly mutates the array, so don’t reassign it back to the original variable.
The ‘splice’ method can be used to remove/replace elements in an array, and we can specify the number of elements we want replaced as well.
In our case, we want the removal to happen from the ‘length’ index, and we want the str.length – length elements to be removed from that position (the remaining elements after the truncation), as shown below:
str = str.split(''); str.splice(length,str.length - length); str = str.join('');
Using the filter method
Also, you can use the ‘filter’ method after using the ‘split’ method as well. This method can be used to ‘filter’ elements of an array based on a condition.
It iterates through an array, just like in a loop, and for every iteration, you get the current element’s value in a temporary variable. You can use this value to do your condition check.
For our purposes though, we’re going to be going a step further. We’re going to receive the index of the current iteration as well.
This way, we can check that the index is not more than the length. As long as its length is less than the index, it’ll be included in the array, and the rest will be left out.
Finally, you can join the newly formed array using the ‘join’ method, as shown below:
str = str.split('').filter((s,index) => index < length).join('');
Trim the string before truncating it
Sometimes, your string might have leading or trailing spaces that have no use for you. You don’t need these spaces to take up the length of your truncated string.
So, you can use the trim() method to remove all the extra spaces, and then truncate the trimmed string, as shown below:
const truncateString = (str,length) => { str = str.trim().slice(0,length); return str; } console.log(truncateString(" Hello there, how are you? This is a fine day, isn't it? ",25)); //Hello there, how are you...
Manually truncate a string using loops
Finally, let’s look at manually truncating our string. There’s always our trusty ‘for’ loop that can be used to loop through our string.
For this method, we need a separate variable where we’ll be storing the truncated string. This variable will be assigned an empty string as the starting value. For every iteration of the loop, check if the current value of ‘i’ is less than the given ‘length’. If it Is, concatenate the str[i] character to the truncatedStr string, as shown below:
const truncateString = (str,length) => { str = str.trim(); let truncatedStr = ''; for(let i = 0; i <= length; i++) { truncatedStr += str[i]; } return truncatedStr; } console.log(truncateString(" Hello there, how are you? This is a fine day, isn't it? ",25)); //Hello there, how are you...
That’s it! We’ve looked at how to truncate a string in JavaScript, including using pre-defined methods and manual loops.