Getting Name initials using JS
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
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);
You can use this shorthand js
"FirstName LastName".split(" ").map((n)=>n[0]).join(".");
To get only First name and Last name you can use this shorthand function
(fullname=>fullname.map((n, i)=>(i==0||i==fullname.length-1)&&n[0]).filter(n=>n).join(""))
("FirstName MiddleName OtherName LastName".split(" "));