I am currently having trouble with this code. I have prompted the user to input a number of at least 3 digits, and the aim here is to create an output that will give the user the same number but with the 2nd and last digits swapped.
The problem I am having is that when the input is more than 3 digits there are some other digits missing (e.g. input = 5442, the console.log() will give 524: The digits have been swapped, however the the third digit is now missing).
The code works perfectly with a 3-digit input.
let userInput = (prompt("Please enter a number with at least 3 digits: "));
//validating user input
while(isNaN(userInput) ||userInput.length < 3){
userInput = prompt ("Invalid input. Please enter a number with at least 3 digits: ");
}
//converting input to string for easier manipulation
let userInputStr = userInput.toString()
//swap second and last digits using for loop
for(let i = 0; i < 1; i++){ // loop will run only once
let secondNum = userInputStr[1];
// substring used to extract the middle section of the original string
userInputStr = userInputStr[0] + userInputStr[userInputStr.length -1] + userInputStr.substring(0,length-1) + secondNum;
}
// Output original and new numbers
console.log(`Original Number: ${userInput}`);
console.log(`New Number: ${userInputStr}`);
I’ve even added a substring(0, length-1) to include the first number and the digits in between. Has anyone else experienced this problem before? Please assist?