JavaScript – Check if String ends with Specific Substring

To check if a string str ends with a specific string searchStr in JavaScript, call endsWith() method on this string str, and pass the other string searchStr as argument.

endsWith() method returns a boolean value. The return value is true if specified string is present at the end of this string, or else, it returns false.

Syntax

The syntax to check if string str1 ends with the string searchStr is

</>
Copy
str.endsWith(searchStr)

Examples

The following is a quick example to check if string str1 ends with the string searchStr in JavaScript.

</>
Copy
var str = 'Hello World';
var searchStr = 'World';
var result = str.endsWith(searchStr);

We may use the return value of endsWith() method as a condition in If statement.

</>
Copy
var str = 'Hello World';
var searchStr = 'World';
if ( str.endsWith(searchStr) ) {
    //str ends with specified searchStr
} else {
    //str does not end with specified searchStr
}

In the following example, we take two strings: str and searchStr in script, and check if string str ends with the string searchStr using endsWith() method. We shall display the result in a div.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <div id="output"></div>
    <script>
        var str = 'Hello World';
        var searchStr = 'World';

        if ( str.endsWith(searchStr) ) {
            displayOutput = 'str ends with specified searchStr.';
        } else {
            displayOutput = 'str does not end with specified searchStr.';
        }
        document.getElementById('output').innerHTML = displayOutput;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to check if a string ends with a specified string in JavaScript, using endsWith() method, with examples.