Reputation: 53
I am struggling to figure out how can I refactor my code to get a first letter and last name but if it is only one word to get the word without the first letter. When is only one word getting the first letter as well? E.G If it is [email protected] then becomes [email protected] if it is [email protected] is getting right [email protected] is there a way to fix that? I would really appreciate it if someone can help? Here is my Code:
var fullName = item.getValue('abc12312').toLowerCase().split(' ');
var lastName = fullName[fullName.length - 1];
var firstLetter = fullName[0].charAt(0);
if(fullName != '') {
var email = firstLetter + lastName + '@abc12123.com';
}
Upvotes: 1
Views: 1618
Reputation:
All you need to do is create a function/method that:
Upvotes: 0
Reputation: 366
hadn't tested the code, but mostly it will work
// get input value from HTML and convert it as an array ;
const fullName = document.getElementById('fullname').toLowerCase().split(' ');
let firstLetterOrWord;
if(fullName.length === 1){
// only one word
firstLetterOrWord = fullName[0]
} else {
// two words
// first character of first elemment of array
firstLetterOrWord = fullName[0][0]
}
// if not found -> empty string
const lastName = fullName[1] || '';
const email = firstLetterOrWord + lastName + '@abc12123.com';
<input id="fullname" type="text">
Upvotes: 1
Reputation: 49
You need to understand what every function you've mentioned in your code block does. Also, please define/mention what item is in your codeblock because we do not have any knowledge/reference as to what it is.
// get the full name
var fullName = item.getValue('abc12312').toLowerCase().split(' ');
// get the last name
var lastName = fullName[fullName.length - 1];
// get the first letter
var firstLetter = fullName[0][0]
if (lastName != ''){
const email = firstLetter + lastName + '@abc12123.com';
}else{
const email = fullName[0] + '@abc12123.com';
}
Upvotes: 1