[Javascript] How to trim a string to specific length?


I want to trim a string to specific length, How to do that in Javascript?

1 Answer

3 years ago by

You can use either substring() or slice() methods to trim a string to given length. Check the usage as shown below:

let str= 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';

let givenLength = 15;

console.log(str.substring(0, givenLength));

console.log(str.slice(0, givenLength))

Run here https://onecompiler.com/javascript/3xnrpear6

3 years ago by Meera