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

102 thoughts on “Getting Name initials using JS”

  1. 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);
    Reply
  2. just updated Andrea’s version:

    var getInitials = function (string) {
       var initials = "";
       var names = string.split(' ');
       for (n = 0; n < names.length; n++) {
            initials += names[n].substring(0, 1).toUpperCase();
        }
        return initials;
    };
    

    if string includes LastName, just change names.length to names.length-1 to ignore lastname

    Reply
  3. Easier with map function:

    var name = "First Last";
    var initials = Array.prototype.map.call(name.split(" "), function(x){ return x.substring(0,1).toUpperCase();}).join('');
    
    Reply
  4. You can do a function for that:

    var name = 'Name';
    
    function getInitials( name,delimeter ) {
    
        if( name ) {
    
            var array = name.split( delimeter );
    
            switch ( array.length ) {
    
                case 1:
                    return array[0].charAt(0).toUpperCase();
                    break;
                default:
                    return array[0].charAt(0).toUpperCase() + array[ array.length -1 ].charAt(0).toUpperCase();
            }
    
        }
    
        return false;
    
    }
    

    Fiddle: http://jsfiddle.net/5v3n2f95/1/

    Reply
  5.   const getInitials = name => {
        let initials = '';
        name.split(' ').map( subName => initials = initials + subName[0]);
        return initials;
      };
    
    Reply
  6. Check the getInitials function below:

    var getInitials = function (string) {
        var names = string.split(' '),
            initials = names[0].substring(0, 1).toUpperCase();
        
        if (names.length > 1) {
            initials += names[names.length - 1].substring(0, 1).toUpperCase();
        }
        return initials;
    };
    
    console.log(getInitials('FirstName LastName'));
    console.log(getInitials('FirstName MiddleName LastName'));
    console.log(getInitials('1stName 2ndName 3rdName 4thName 5thName'));

    The functions split the input string by spaces:

    names = string.split(' '),
    

    Then get the first name, and get the first letter:

    initials = names[0].substring(0, 1).toUpperCase();
    

    If there are more then one name, it takes the first letter of the last name (the one in position names.length - 1):

    if (names.length > 1) {
        initials += names[names.length - 1].substring(0, 1).toUpperCase();
    }
    
    Reply
  7. const getInitials = name => name
      .replace(/[^A-Za-z0-9À-ÿ ]/ig, '')        // taking care of accented characters as well
      .replace(/ +/ig, ' ')                     // replace multiple spaces to one
      .split(/ /)                               // break the name into parts
      .reduce((acc, item) => acc + item[0], '') // assemble an abbreviation from the parts
      .concat(name.substr(1))                   // what if the name consist only one part
      .concat(name)                             // what if the name is only one character
      .substr(0, 2)                             // get the first two characters an initials
      .toUpperCase();                           // uppercase, but you can format it with CSS as well
    
    console.log(getInitials('A'));
    console.log(getInitials('Abcd'));
    console.log(getInitials('Abcd Efgh'));
    console.log(getInitials('Abcd    Efgh    Ijkl'));
    console.log(getInitials('Abcd Efgh Ijkl Mnop'));
    console.log(getInitials('Ábcd Éfgh Ijkl Mnop'));
    console.log(getInitials('Ábcd - Éfgh Ijkl Mnop'));
    console.log(getInitials('Ábcd / # . - , Éfgh Ijkl Mnop'));
    
    Reply
  8. You can do something like this;

        function initials(name){
    
          //splits words to array
          var nameArray = name.split(" ");
    
          var initials = '';
    
          //if it's a single word, return 1st and 2nd character
          if(nameArray.length === 1) {
            return nameArray[0].charAt(0) + "" +nameArray[0].charAt(1);
          }else{
             initials = nameArray[0].charAt(0);
          }
          //else it's more than one, concat the initials in a loop
          //we've gotten the first word, get the initial of the last word
    
    
          //first word
          for (i = (nameArray.length - 1); i < nameArray.length; i++){
            initials += nameArray[i].charAt(0);
          }
         //return capitalized initials
         return initials.toUpperCase();
       }
    

    You can then use the function like so;

      var fullname = 'badmos tobi';
      initials(fullname); //returns BT 
    
      var surname = 'badmos';
      initials(surname); //returns BA
    
      var more = 'badmos gbenga mike wale';
      initials(more); //returns BW;
    

    I hope this helps.

    Reply
  9. 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(" "));
    
    Reply
  10. Using some es6 functionality:

    const testNameString = 'Hello World';
    const testNameStringWeird = 'Hello  darkness My  - Óld Friend Nikolaus Koster-Walder ';
    const getInitials = nameString =>{
           const regexChar = /\D\w+/
           return nameString
            .trim() //remove trailing spaces
            .split(' ') // splits on spaces
            .filter(word => word.length > 0) // strip out double spaces
            .filter(word => regexChar.test(word)) // strip out special characters
            .map(word => word.substring(0, 1).toUpperCase()) // take first letter from each word and put into array
    }
    console.log('name:',testNameString,'\n initials:',getInitials(testNameString));
    console.log('name:',testNameStringWeird,'\n initials:',getInitials(testNameStringWeird));
    Reply
  11. You use below one line logic:

    "FirstName MiddleName LastName".split(" ").map((n,i,a)=> i === 0 || i+1 === a.length ? n[0] : null).join("");
    
    Reply
  12. This solution uses Array capabilities, Arrow function and ternary operator to achieve the goal in one line.
    If name is single word, just take first two chars, but if more, then take 1st chars of first and last names.
    (thanks omn for reminding single word name use case)

    string.trim().split(' ').reduce((acc, cur, idx, arr) => acc + (arr.length > 1 ? (idx == 0 || idx == arr.length - 1 ? cur.substring(0, 1) : '') : cur.substring(0, 2)), '').toUpperCase()
    
    Reply
  13. var personName = "FirstName MiddleName LastName";
    var userArray = personName.split(" ");
    var initials = [];
    if(userArray.length == 1){
     initials.push(userArray[0][0].toUpperCase() + userArray[0][1]).toUpperCase();}
    else if(userArray.length > 1){
    initials.push(userArray[0][0].toUpperCase() + userArray[userArray.length-1][0].toUpperCase());}
    console.log(initials);
    
    Reply
  14. This should work for majority of the cases including middle names and first name only (extension on @njmwas answer).

    const initialArr = name.split(" ").map((n)=>n[0]);
    const init = (initialArr.length > 1)? `${initialArr[0]}${initialArr[initialArr.length - 1]}` : initialArr[0];
    const initials = init.toUpperCase();
    
    Reply
  15. I saw a bunch of overcomplicated ways to do this.
    I’m really more into simplifying things as much as possible, and enhance things using composition or currying.

    Here are my 2 cents:

    
    // Helpers
    
    const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
    const reverseText = (text = '')=> text.split('').reverse().join('');
    
    const getInitialsDelimitBy = (delimiter = ' ') => (displayName = '') =>
      displayName
        .trim()
        .split(delimiter)
        .reduce((acc, value) => `${acc}${value.charAt(0)}`, '')
        .toUpperCase();
    
    const getInitialsDelimitByComas = pipe(
      getInitialsDelimitBy(','), 
      reverseText
    );
    
    const getInitialsDelimitBySpaces = getInitialsDelimitBy(' '); // Not necessary because of the default but clearer 
    
    const comaInitials = getInitialsDelimitByComas('Wayne, Bruce') // BW
    const spaceInitials = getInitialsDelimitBySpaces('Bruce Wayne') // BW
    

    For your specific case I would suggest something like this:

    const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
    
    const nameProcessor = {
      single: (name = '') =>
        name
          .trim()
          .substring(0, 2)
          .toUpperCase(),
      multiple: pipe(
        name => name.trim().split(' '),
        words => `${words[0].charAt(0)}${words[words.length - 1].charAt(0)}`,
        initials => initials.toUpperCase(),
      ),
    };
    
    const getInitials = (displayName = '') => 
      displayName.split(' ').length === 1 
        ? nameProcessor.single(displayName) 
        : nameProcessor.multiple(displayName)
    
    getInitials('FullName') // FU
    getInitials('FirstName MiddleName LastName') // FL
    getInitials('1stName 2ndName 3rdName 4thName 5thName') // 15
    

    I hope that helps =D

    Reply
  16. To get the first name and last name initials, try using the function below.

    const getInitials = string => {
        const names = string.split(' ');
        const initials = names.map(name => name.charAt(0).toUpperCase())
        if (initials.length > 1) {
            return `${initials[0]}${initials[initials.length - 1]}`;
        } else {
            return initials[0];
        }
    };
    console.log(getInitials("1stName 2ndName 3rdName 4thName 5thName")); // 15
    console.log(getInitials("FirstName MiddleName LastName")); // FL
    

    WHAT HAPPENED: The function splits the incoming string, ignores any name between the first & last names and returns their initials. In the case a single name is entered, a single initial is returned. I hope this helps, cheers.

    Reply
  17. Easy way using ES6 Destructering:

    const getInitials = string =>
      string
        .split(' ')
        .map(([firstLetter]) => firstLetter)
        .filter((_, index, array) => index === 0 || index === array.length - 1)
        .join('')
        .toUpperCase();
    
    Reply
  18. Just surprised that none of the answers put reduce to good use.

    Using Array.reduce(), you could do something like –

    const getInitials = (fullName) => {
      const allNames = fullName.trim().split(' ');
      const initials = allNames.reduce((acc, curr, index) => {
        if(index === 0 || index === allNames.length - 1){
          acc = `${acc}${curr.charAt(0).toUpperCase()}`;
        }
        return acc;
      },['']);
      return initials;
    }
    

    Run the snippet below to check the initials for different use cases –

    const testNames = [
      'Albus Percival Wulfric Brian dumbledore',
      'Harry Potter',  
      'Ron',
      '',
      'Çigkofte With Érnie',
      'Hermione ',
      'Neville LongBottom '
    ]
    
    const getInitials = (fullName) => {
      const allNames = fullName.trim().split(' ');
      const initials = allNames.reduce((acc, curr, index) => {
        if(index === 0 || index === allNames.length - 1){
          acc = `${acc}${curr.charAt(0).toUpperCase()}`;
        }
        return acc;
      },['']);
      return initials;
    }
    
    
    console.log(testNames.map(getInitials));

    Note: This one is for a widely used case for displaying names in Avatars, where you wouldn’t want first name initial to be repeated twice and want to restrict the initials to a max of 2 letters

    Reply
  19. There are some other answers which solve your query but are slightly complicated. Here’s a more readable solution which covers most edge cases.

    As your full name can have any number of words(middle names) in it, our best bet is to spit it into an array and get the initial characters from the first and last words in that array and return the letters together.

    Also if your ‘fullName’ contains only one word, word at array[0] and array[array.length - 1] would be the same word, so we are handling that if the first if.

    function nameToInitials(fullName) {
      const namesArray = fullName.trim().split(' ');
      if (namesArray.length === 1) return `${namesArray[0].charAt(0)}`;
      else return `${namesArray[0].charAt(0)}${namesArray[namesArray.length - 1].charAt(0)}`;
    }
    

    Sample outputs :

    > nameToInitials('Prince') // "P"

    > nameToInitials('FirstName LastName') // "FL"

    > nameToInitials('1stName 2ndName 3rdName 4thName 5thName')
    // "15"

    Reply
  20. Shortest One Liners:

    Get First and Last Initial: John Doe Smith => JS

    name.match(/(\b\S)?/g).join("").match(/(^\S|\S$)?/g).join("").toUpperCase()
    

    Get All Initials: "John Doe Smith" => "JDS"

    name.match(/(\b\S)?/g).join("").toUpperCase()
    

    Get First and Last except get First 2 in case there is only first. (OP’s question)

    John => JO and "John Doe Smith" => "JS"

    name.match(/(^\S\S?|\b\S)?/g).join("").match(/(^\S|\S$)?/g).join("").toUpperCase()
    

    Note: If the name contains , or other non word characters, you might use /w instead of /S or sanitize it beforehand

    Reply
  21. One more way to do the same.

    function getInitials(str) {
      const FirstName = str.split(' ')[0];
      const LastName = str.split(' ').reduceRight(a => a);
    
      // Extract the first two characters of a string
      if (FirstName === LastName) {
        return FirstName.trim()
          .substring(0, 2)
          .toUpperCase();
      }
    
      // Abbreviate FirstName and LastName
      return initials = [FirstName, LastName]
        .map(name => name[0])
        .join('').toUpperCase();
    }
    
    console.log(getInitials('FullName'));
    console.log(getInitials('FirstName MiddleName LastName'));
    console.log(getInitials('1stName 2ndName 3rdName 4thName 5thName'));
    Reply

Leave a Comment