For and while loops

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?

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

it’s already a string

here you have length that is not defined, I guess substring is not returning what you want

if you check the value of userInputStr.substring(0,length-1) it is an empty string

1 Like