JavaScript - endsWith() method

revision:


Category : string

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false. The endsWith() method is case sensitive.

Syntax :

        string.endsWith(searchvalue, length)
    

Parameters:

searchvalue : required. The string to search for.

length : optional. The length of the string to search. Default value is the length of the string..

Examples:

        <p>Check if "Hello world" ends with "world":</p>
        <p id="demo"></p>
        <script>
            let text = "Hello world";
            let result =  text.endsWith("world");
            document.getElementById("demo").innerHTML = result;
        </script>

    

Practical examples

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

code:
                    <div>
                        <p id="end-1"></p>
                        <p id="end-2"></p>
                        <p id="end-3"></p>
                        <p id="end-4"></p>
                        <p id="end-5"></p>
                    </div>
                    <script>
                        let text = "Hello world";
                        document.getElementById("end-1").innerHTML = "string : " + text;
                        let result = text.endsWith("world");
                        document.getElementById("end-2").innerHTML = "ends with 'world' = " + result;
                        let result1 = text.endsWith("World");
                        document.getElementById("end-3").innerHTML = "ends with 'World' = " + result1;
                        
                        let str = "Hello world, welcome to the universe.";
                        document.getElementById("end-4").innerHTML = "string : " + str;
                        document.getElementById("end-5").innerHTML = str.endsWith("world", 11);
                        
                    </script>