JavaScript - split() method

revision:


Category : string

The split() method splits a string into an array of substrings. It returns the new array, but does not change the original string. If (" ") is used as separator, the string is split between words.

Syntax :

        string.split(separator, limit)
    

Parameters:

separator : optional. A string or regular expression to use for splitting.If omitted, an array with the original string is returned.

limit : optional. An integer that limits the number of splits. Items after the limit are excluded.

Examples:

        <p>split() splits a string into an array of substrings, and returns the array:</p>
        <p id="demo"></p>
        <script>
            let text = "How are you doing today?";
            const myArray = text.split(" ");
            document.getElementById("demo").innerHTML = myArray; 
        </script>
    

Practical examples

example: split the words

code:
                    <div>
                        <p id="split-1"></p>
                        <p id="split-2"></p>
                        <p id="split-3"></p>
                        <p id="split-4"></p>
                        <p id="split-5"></p>
                        <p id="split-6"></p>
                        <p id="split-7"></p>
                        <p id="split-8"></p>
                        <p id="split-9"></p>
                        <p id="split-10"></p>
            
                    </div>
                    <script>
                        let text = "How are you doing today?";
                        document.getElementById("split-1").innerHTML = "sentence : " + text;
                        const myArray = text.split(" ");
                        document.getElementById("split-2").innerHTML = "new array : " + myArray; 
                        document.getElementById("split-3").innerHTML = "new array - limit 1 : " + myArray[1];
                        document.getElementById("split-4").innerHTML = "new array - limit 0 : " + myArray[0];
                        const myArray1 = text.split("");
                        document.getElementById("split-5").innerHTML = "new array : " + myArray1;
                        const myArray2 = text.split(" ", 3);
                        document.getElementById("split-6").innerHTML = "new array : " + myArray2;
                        const chars = text.split("");
                        document.getElementById("split-7").innerHTML = "characters : " + chars[1];
                        const myArray3 = text.split("o");
                        document.getElementById("split-8").innerHTML = "new array : " + myArray3;
                        const myArray4 = text.split();
                        document.getElementById("split-9").innerHTML = "new array : " + myArray4;
                    </script>