Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abbreviate a two word name in JavaScript

Tags:

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!

like image 293
Momin Avatar asked May 06 '20 09:05

Momin


People also ask

How do you abbreviate words in JavaScript?

JS. Sometimes, it's also used to abbreviate Javascript. Related words: JTOT.


1 Answers

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
like image 120
Justinas Avatar answered Sep 24 '22 23:09

Justinas