JavaScript Code


How to check if string ends with forward slash / character using JavaScript?


Check if string ends with /

Given a string, check if the string ends with the forward slash character (/) using JavaScript.

Solution

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

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

Program

1. Given string is str. Check if string str ends with / character.

str = "https://javascriptcode.org/";
ch = "/";

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