JavaScript - substr() method

revision:


Category : string

The substr() method extracts a part of a string. It begins at a specified position, and returns a specified number of characters. The method does not change the original string.To extract characters from the end of the string, use a negative start position.

Syntax :

        string.substr(start, length)
    

Parameters:

start : required. The start position. First character is at index 0. If start is greater than the length, substr() returns "". If start is negative, substr() counts from the end of the string.

length : optional. The number of characters to extract.If omitted, it extracts the rest of the string.

Examples:

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

Practical examples

example: substr() 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>
                    </div>
                    <script>
                        let text = "Hello world!";
                        document.getElementById("sub-1").innerHTML = " text : " + text;
                        let result = text.substr(1, 4);
                        document.getElementById("sub-2").innerHTML = "substr : " + result;
                        let result1 = text.substr(2);
                        document.getElementById("sub-3").innerHTML = "substr : " + result1;
                        let result2 = text.substr(0, 1);
                        document.getElementById("sub-4").innerHTML = "substr : " + result2;
                        let result3 = text.substr(text.length-1, 1);
                        document.getElementById("sub-5").innerHTML = "substr : " + result3;
                        let result4 = text.substr(text.length-6, 6);
                        document.getElementById("sub-6").innerHTML = "substr : " + result4;
            
                    </script>