1

Quick question. Let's say you have a string of three numbers separated by spaces, like so: "123 5235 90" and the length of each number varies. How could one go about pulling each number to a variable so that number1 = 123 number2 = 5235 and number3 = 90. Any input is appreciated. Thanks!

1

1 Answer 1

2

You can use split alongside destructuring:

const s = "123 5235 90"
const [number1, number2, number3] = s.split(' ')

console.log(number1)
console.log(number2)
console.log(number3)

Should you want the output to be actual numbers instead of strings, you can map over the split like so to convert all elements to numbers:

s.split(' ').map(Number)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.