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);

3 answers

  • answered 2017-11-12 20:28 Konrad D

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

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

  • answered 2017-11-12 20:28 davidxxx

    Use String.split by specifying a whitespace as separator.

    The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.

    For example :

    let inputFromPrompt = prompt("Enter"); 
    // then enter "Hello World!"
    let token = inputFromPrompt.split(' ');
    

  • answered 2017-11-12 20:41 Walter Chapilliquen - wZVanG

    Your expected result is like that?

    let items = [], action, i = 1;
      
    while(action = prompt(`Enter ${i++}`)){
       items = items.concat(action.split(" "));
    }
      
    console.log(items);
    
    //Enter 1: hello world
    //Enter 2: four five
    //[Cancel] prompt
    
    //Result: ["hello", "world", "four", "five"]

    .split(" ") : Separate words by space

    .concat(items) : To merge the current array with the previous array