I would like to extract initials from a string, like:
Name = FirstName LastName Initials = FL
I can get the above result using this,
const initials = item .FirstName .charAt(0) .toUpperCase() + item .LastName .charAt(0) .toUpperCase();
But now my requirements are changed as if name only consist of 1 word or more then 2, so in following cases how can I get initials as per my requirements,
FullName = FU FirstName MiddleName LastName = FL 1stName 2ndName 3rdName 4thName 5thName = 15
How can I get above initials from a string in JS?
Also now I only have item.Name
string as an input
Get the First Letter of the String You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str. charAt(0) returns an empty string ( '' ) for str = '' instead of undefined in case of ''[0] .
innerHTML = first + " " + second; The G and I should be lower case and you should output both first and last names at the same time using string concatenation.
Why no love for regex?
Updated to support unicode characters and use ES6 features
let name = 'ÇFoo Bar 1Name too ÉLong'; let rgx = new RegExp(/(\p{L}{1})\p{L}+/, 'gu'); let initials = [...name.matchAll(rgx)] || []; initials = ( (initials.shift()?.[1] || '') + (initials.pop()?.[1] || '') ).toUpperCase(); console.log(initials);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With