JavaScript Code


How to check if string ends with specific suffix string using JavaScript?


Check if string ends with specific suffix

Given a string and suffix string, check if the string ends with the given suffix string using JavaScript.

Solution

To check if a string ends with a specific suffix string using JavaScript, we can use String.endsWith() method. Call endsWith() method on the string, and pass the suffix string as argument.

endsWith() returns true if the string ends with the given suffix string, or false if the string does not end with the given suffix string.

Program

1. given string is str and suffix string is suffix. check if string str ends with suffix

str = "hello world";
suffix = "orld";

if ( str.endsWith(suffix) ) {
    console.log('string ends with given suffix');
} else {
    console.log('string does not end with given suffix');
}