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!
JS. Sometimes, it's also used to abbreviate Javascript. Related words: JTOT.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With