JavaScript Program to Truncate a String to a Certain Length
Last Updated :
10 Oct, 2023
In this article, we are going to learn how can we truncate a string to a certain length. Truncating a string to a certain length in JavaScript means shortening a string so that it doesn’t exceed a specified maximum length. This can be useful for displaying text in user interfaces, such as titles or descriptions while ensuring that the text does not exceed a certain number of characters.
Using JavaScript String slice method
This approach uses the slice() method to extract a portion of the string up to the desired length.
Example: This example shows the use of the above-explained approach.
Javascript
function gfgFun(str, MaxLength) {
if (str.length > MaxLength) {
return str.slice(0, MaxLength);
} else {
return str;
}
}
const str = "gfg is a good place for growth" ;
const MaxLength = 20;
console.log(gfgFun(str, MaxLength));
|
Output
gfg is a good place
Using JavaScript String substring method
This approach uses the substring() method to get a substring up to the specified length.
Example: This example shows the use of the above-explained approach.
Javascript
function gfgFun(str, maxLength) {
if (str.length > maxLength) {
return str.substring(0, maxLength);
} else {
return str;
}
}
const str = "gfg is a good place for growth" ;
const maxLength = 20;
console.log(gfgFun(str, maxLength));
|
Output
gfg is a good place
Share your thoughts in the comments
Please Login to comment...