JavaScript - startsWith() method

revision:


Category : string

The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false. The startsWith() method is case-sensitive.

Syntax :

        string.startsWith(searchvalue, start)
    

Parameters:

searchvalue : required. The string to search for.

starth : optional. Start position. Default value is 0.

Examples:

        <p>startsWith() returns true if a string starts with a specified string:</p>
        <p id="demo"></p>
        <script>
            let text = "Hello world, welcome to the universe.";
            let result = text.startsWith("Hello");
            document.getElementById("demo").innerHTML = result;
        </script>
    

Practical examples

example: check if a string starts with "...".

code:
                    <div>
                        <p id="start-1"></p>
                        <p id="start-2"></p>
                        <p id="start-3"></p>
                        <p id="start-4"></p>
                        <p id="start-5"></p>
                    </div>
                    <script>
                        let text = "Hello world, welcome to the universe.";
                        document.getElementById("start-1").innerHTML = "string : " + text;
                        let result = text.startsWith("Hello");
                        document.getElementById("start-2").innerHTML = "starts with 'Hello' = " + result;
                        let result1 = text.startsWith("Hello", 1);
                        document.getElementById("start-3").innerHTML = "starts with 'Hello' = " + result1;
                        document.getElementById("start-4").innerHTML = "starts with 'Hello' = " + text.startsWith("Hello", 0);
                        
                    </script>