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

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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.