Momin
Momin

Reputation: 3320

Abbreviate a two word name in JavaScript

I'm writing a function to convert a name into initials. This function return strictly takes two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should be like this:

alex cross => A.C

jaber ali => J.A

Here is my solution

function initialName(firstLetterFirstName, firstLetterLastName) {
    'use strict'
    let x = firstLetterFirstName.charAt(0).toUpperCase();
    let y = firstLetterLastName.charAt(0).toUpperCase();
    return x + '.' + y;
}

console.log(initialName('momin', 'riyadh'));  // M.R

Have I solved this problem with hardcoded, and my approach is right? or could it be better!

Upvotes: 5

Views: 5475

Answers (4)

Mark  Partola
Mark Partola

Reputation: 674

Try this:

name.split(' ').map(el => el[0]).join('.').toUpperCase()

In you case with multiple parts could be like this:

function make(...parts) {
   return parts.map(el => el[0]).join('.').toUpperCase()
}

Upvotes: 2

Abdul Basit
Abdul Basit

Reputation: 1382

You can try this

    var str = "Abdul Basit";
    var str1 = "This is a car";
    console.log(getInitials(str));
    console.log(getInitials(str1));
    
    function getInitials(str) {
      var matches = str.match(/\b(\w)/g);
      return matches.join('.').toUpperCase();
    }

Upvotes: 1

Justinas
Justinas

Reputation: 43479

Use regex for that:

function initialName(words) {
    'use strict'
    
    return words
        .replace(/\b(\w)\w+/g, '$1.')
        .replace(/\s/g, '')
        .replace(/\.$/, '')
        .toUpperCase();
}

console.log(initialName('momin riyadh'));  // M.R
console.log(initialName('momin riyadh ralph')); // M.R.R

Upvotes: 7

Nino Filiu
Nino Filiu

Reputation: 18493

It works, but it could be written in a one-liners:

console.log(
  ['john', 'doe']
  .map(word => `${word[0].toUpperCase()}.`).join('')
)

Upvotes: 0

Related Questions