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!

Charles Pettis
  • 337
  • 1
  • 3
  • 11
  • Does this answer your question? [javascript: split string straight to variables](https://stackoverflow.com/questions/3522406/javascript-split-string-straight-to-variables) – Ivar Dec 04 '19 at 15:13

1 Answers1

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)
Kobe
  • 6,226
  • 1
  • 14
  • 35