How to use the slice() method In Javascript
In this approach, we are using the slice() method that extracts a section of the string and returns it as a new string without the modifying the original string.
Example: Truncate a String in JavaScript using the slice() method.
function GFG(str, maxLength) {
if (str.length > maxLength) {
return str.slice(0, maxLength) + '...';
}
return str;
}
const longText = "w3wiki , Learning.";
const truncatedText = GFG(longText, 20);
console.log(truncatedText);
Output
w3wiki , Lear...
How to Truncate a String in JavaScript ?
In JavaScript, there are several ways to truncate a string which means cutting off a part of the string to limit its length. Truncating a string is useful when we want to display only a certain number of the characters in the user interfaces such as previewing a longer text or ensuring that text fits within the specified space.
Use the below methods to Truncate a String in JavaScript:
Table of Content
- Using the substring() method
- Using the slice() method
Contact Us