Search code examples
javascriptarraysprompt

Split result of 'prompt()' into items in an array?


Question

How can I add multiple values to a list just by using one prompt();?

Code

let items = [];
action = prompt("Enter");

If my input is Hello World!, then how can I make my list looking like this:

items = ["Hello", "World!"];

Attempts

This is the closest that I can get (it failed becasue I can only use one prompt();):

let first = prompt("Enter 1");
let second = prompt("Enter 2");
items.push(first);
items.push(second);

Solution

  • You can split the received string to get an array with two separate values.

    let action = prompt();
    let items = action.split(' ');
    
    console.log(items);