WebMasterCampus
WEB DEVELOPER Resources

Convert a String to an Array in Javascript

Learn how Convert a String to an Array in Javascript


JavsScript .split("")

    const msg = "Hello WebMasterCampus Programming! Are you beginner?";

    msg_array = msg.split(" ");

    // Use index to get or set individual values.
    console.log(msg_array[0]);
    console.log(msg_array[1]);

    console.log(msg_array.length);

    // Display all values using basic for Loop
    for(i=0; i <msg_array.length ; i++){
        console.log(msg_array[i])
    }

    // Display all values using forEach Loop
    msg_array.forEach(element => {
        console.log(element);
    });

JavaScript ES2015 spread syntax

    const msg = "Hello WebMasterCampus Programming! Are you beginner?";
    const msg_array = [...msg];
    console.log(msg_array);

JavaScript Object.assign([], str)

    const msg = "Hello WebMasterCampus Programming! Are you beginner?";
    const msg_array = Object.assign([], msg);
    console.log(msg_array);

JavaScript Array.from(str)

    const msg = "Hello WebMasterCampus Programming! Are you beginner?";
    const msg_array = Array.from(msg1);
    console.log(msg_array);

JavaScript Array.prototype.slice.call(“string”)

    const msg = "Hello WebMasterCampus Programming! Are you beginner?";
    const msg_array = Array.slice.call(msg);
    console.log(msg_array);

JavaScript for loop & array.push

    const msg = "Hello WebMasterCampus Programming! Are you beginner?";
    msg_array = [];

    for (const item of msg){
        msg_array.push(item);
    }

    console.log(msg_array);
Created with love and passion.