JavaScript - substring() method

revision:


Category : string

The substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The method extracts characters from start to end (exclusive) and does not change the original string.
If "start" is greater than "end", arguments are swapped: (4, 1) = (1, 4). "Start" or "end" values less than 0, are treated as 0.

Syntax :

        string.substring(start, end)
    

Parameters:

start : required. The start position. First character is at index 0.

end : optional. End position (up to, but not including). If omitted: the rest of the string.

Examples:

        <p>substring() extracts a part of a string:</p>
        <p id="demo"></p>
        <script>
            let text = "Hello world!";
            let result = text.substring(1, 4);
            document.getElementById("demo").innerHTML = result;
        </script>
    

Practical examples

example: the substring() method extracts a part of a string.

code:
                    <div>
                        <p id="sub-1"></p>
                        <p id="sub-2"></p>
                        <p id="sub-3"></p>
                        <p id="sub-4"></p>
                        <p id="sub-5"></p>
                        <p id="sub-6"></p>
                        <p id="sub-7"></p>
                    </div>
                    <script>
                        let text = "Hello world!";
                        document.getElementById("sub-1").innerHTML = " text : " + text;
                        let result = text.substring(1, 4);
                        document.getElementById("sub-2").innerHTML = "substring : " + result;
                        let result1 = text.substring(2);
                        document.getElementById("sub-3").innerHTML = "substring : " + result1;
                        let result2 = text.substring(4, 1);
                        document.getElementById("sub-4").innerHTML = "substr : " + result2;
                        let result3 = text.substring(-3);
                        document.getElementById("sub-5").innerHTML = "substr : " + result3;
                        let result4 = text.substring(0, 1);
                        document.getElementById("sub-6").innerHTML = "substr : " + result4;
                        let result5 = text.substring(text.length -1);
                        document.getElementById("sub-7").innerHTML = "substr : " + result5;
            
                    </script>