Reputation: 3320
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
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
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
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
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