Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 891
Mathematics Avatar asked Oct 12 '15 08:10

Mathematics


People also ask

How do you get the first letter in a string JavaScript?

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] .

How do you join first and last name in JavaScript?

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.


1 Answers

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);
like image 133
Shanoor Avatar answered Sep 25 '22 15:09

Shanoor