Truncating a String using JavaScript
Overview
Truncating a string is a common requirement in JavaScript, especially in user interfaces where space is limited. This snippet shows how to truncate a string to a specified length, optionally adding ellipses to indicate that the text has been shortened.
Code
String Truncation Function
function truncateString(str, num) {
if (str.length <= num) {
return str;
}
return str.slice(0, num) + "...";
}
Example Usage
Truncating a String
const longString = "This is a very long string that needs to be truncated.";
const truncated = truncateString(longString, 25);
console.log("Truncated String:", truncated);
Code Description
The truncateString
function efficiently truncates a string:
- Purpose: To shorten a string to a specified length and append ellipses ('...') if the string exceeds that length.
- Implementation: Checks if the string's length is less than or equal to the desired length. If not, it truncates the string using
slice()
and appends '...'. - Parameters:
str
: The string to be truncated.num
: The maximum length of the string after truncation.
- Return Value: The truncated string, with ellipses added if it was cut off.
This function is particularly useful in scenarios where text length must be limited, such as in tooltips, card views, or summaries in web applications.