I was taking on a JS challenge to take a first/last name string input and do the following:
- swap the first letter of first/last name
- convert all characters to lowercase, except for the first characters, which need to be uppercase
Example:
input: DonAlD tRuMp
output: Tonald Drump
The following is the code I came up with:
const input = prompt("Enter a name:")
function switchFirstLetters(input) {
let stringArray = input.split('');
for(let i=0; i < stringArray.length; i ) {
if(stringArray[i - 1] === ' ') {
[stringArray[0], stringArray[i]] = [stringArray[i], stringArray[0]]; // destructuring
}
}
return result = stringArray.join('');
}
let swappedString = switchFirstLetters(input);
function capFirstLetters(swappedString) {
let stringArray = swappedString.toLowerCase();
stringArray = stringArray.split('');
stringArray[0] = stringArray[0].toUpperCase();
for(let i=0; i < stringArray.length; i ) {
if(stringArray[i - 1] === ' ') {
stringArray[i] = stringArray[i].toUpperCase();
}
}
return result = stringArray.join('');
}
let finalString = capFirstLetters(swappedString);
console.log(finalString);
My thought process for the switchFirstLetters
function was:
- Create an array from the string parameter
- Run through the array length. If the value of the element prior the current element is equal to
' '
, use destructuring to swap the current element with the element at index 0 - Concatenate elements into a new string and return that value
My thought process for the capFirstLetters
function:
- Convert all characters in the string to lowercase (this could be handled outside of the function as well)
- Create an array from the new, lowercase string
- Make character at index 0 be uppercase (this could also be integrated into the for loop)
- Run through the array length. If the value of the element prior to the current element is equal to
' '
, convert that element to uppercase. - Concatenate array elements into a new string
The code works, but I'm still early in my coding journey and realize it's likely not an ideal solution, so I was wondering if anyone here could help me optimize this further to help me learn. Thanks!
CodePudding user response:
You could also use a regular expression to replace the first letters:
let name = "DonAlD tRuMp";
let result = name.toLowerCase().replace(/(\S)(\S*\s )(\S)/g, (_, a, b, c) =>
c.toUpperCase() b a.toUpperCase()
);
console.log(result);
The regular expression uses \S
(a non-white-space character), \S*
(zero or more of those), \s
(one or more white-space characters) and parentheses to create capture groups. These three groups map to a,b,c
parameters in the callback function that is passed to replace
as second argument. With these parts the replacement string can be constructed. Both the capitalisation and the switch happen in the construction.
CodePudding user response:
If the replace function is a little overwhelming, my attempt introduces the for-of loop, the substring string method, array slice as well as the && short circuit evaluation. You should also be aware you can access a given character of a string using the square bracket syntax, just like array, but string has it's own set of methods which tend to have different names.
Definitely take a look at the replace function, to make your v2.
const rawNameInput = "DonAlD jUnior tRuMp"
const nameInput = rawNameInput.trim()
const rawNameWords = nameInput.split(" ")
const nameWords = []
for (const word of rawNameWords) {
const first = word[0].toUpperCase()
const rest = word.substring(1).toLowerCase()
nameWords.push(first rest)
}
const middleNames = nameWords.slice(1, -1).join(" ")
const lastIdx = nameWords.length - 1
const newFirstName = nameWords[lastIdx][0] nameWords[0].substring(1)
const newLastName = nameWords[0][0] nameWords[lastIdx].substring(1)
console.log(`${newFirstName} ${middleNames && middleNames " "}${newLastName}`)