[ Solved -8 Answers] JAVASCRIPT – Get first n characters of a string
How can we get the first n characters of a string in PHP? What’s the fastest way to trim a string to a specific number of characters, and append ‘…’ if needed?
//The simple version for 10 Characters from the beginning of the string.
javascript code
$string = substr($string,0,10).'...‘
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
Sometimes, you need to limit the string to the last complete word ie: you don’t want the last word to be broken instead you stop with the second last word.
eg: we need to limit “This is my String” to 6 chars but instead of ‘This i…” we want it to be ‘This…” ie we will skip that broken letters in the last word.
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.