Skip to content
Advertisement

Keep only first n characters in a string?

Is there a way in JavaScript to remove the end of a string?

I need to only keep the first 8 characters of a string and remove the rest.

Advertisement

Answer

const result = 'Hiya how are you'.substring(0,8);
console.log(result);
console.log(result.length);

You are looking for JavaScript’s String method substring

e.g.

'Hiya how are you'.substring(0,8);

Which returns the string starting at the first character and finishing before the 9th character – i.e. ‘Hiya how’.

substring documentation

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement