- Instant help with your JavaScript coding problems

Check if string ends with slash using JavaScript

Question:
How to check if string ends with slash using JavaScript?
Answer:
const endsWithSlash = (text) => {
    if (!text) {
        return false;
    }
    return text.endsWith('/');
}
Description:

Sometimes it is necessary to know if a particular text ends with a certain character. For example, is there a period at the end of a sentence or a slash character at the end of a URL? Fortunately, this is a very simple task in JavaScript using the endsWith method.

The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

Reference:
endsWith
The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.
JavaScript:
endsWith(searchString, length)
TypeScript:
endsWith(searchString: string, endPosition?: number): boolean;
Examples:
let str = 'To be, or not to be, that is the question.'

console.log(str.endsWith('question.'))  // true
console.log(str.endsWith('to be'))      // false
console.log(str.endsWith('to be', 19))  // true
Share "How to check if string ends with slash using JavaScript?"
Related snippets:
Tags:
string, text, ends, ends with, slash, forward slash, chararcter, check, javascript
Technical term:
Check if string ends with slash using JavaScript