How to Get First 'n' Characters of a String in JavaScript?

Extracting first 'n' chars of a JavaScript string

To get the first "n" number of characters from a JavaScript string, you can use both, String.prototype.substring() or String.prototype.slice(), methods. Both methods will return a new string with the extracted characters. For example:

const str = 'Designcise';

console.log(str.substring(0, 6)); // 'Design'
console.log(str.slice(0, 6)); // 'Design'

If the end index to either argument is greater than the length of the string, then the string's length is used in both cases. For example:

const str = 'foo';

console.log(str.substring(0, 6)); // 'foo'
console.log(str.slice(0, 6)); // 'foo'

For these simple use cases, you can use either of the two methods. However, if start index is greater than end index, or the arguments to either method are negative or NaN, then please be aware of the differences between the two methods.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.