beetle_juice
beetle_juice

Reputation: 53

Get first letter of the string and full last name

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

Answers (3)

user16649222
user16649222

Reputation:

All you need to do is create a function/method that:

  1. accepts that string as an input value
  2. count the number of characters in that supplied string value
  3. if it exceeds 2, than you can use JavaScript indexOf or array index methods to return the first and last.
  4. OR return the first char if it's count is lower than 2.

Upvotes: 0

Mahmoud Hassan
Mahmoud Hassan

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

adist98
adist98

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

Related Questions