The endsWith() method in JavaScript is used to determine whether a string ends with the characters of a specified string. It returns 'true' if the string ends with the specified substring, and 'false' otherwise.
Syntax: string.endsWith(searchString, length)
- searchString: The substring to search for at the end of the string.
- length (optional): The length of the string to consider. If omitted, the entire string is considered.
Example:
let str = "Hello, World!";
let endsWithWorld = str.endsWith("World!");
console.log(endsWithWorld); // Output: true
Explanation:
- We have a string str containing "Hello, World!".
- We use endsWith("World!") to check if the string ends with the substring "World!".
- The method returns 'true' because the string indeed ends with "World!".
We can optionally specify a 'length' argument to limit the portion of the string to be considered for the check. This can be useful if we want to ignore certain characters at the end of the string. If provided, the method checks the substring up to the specified length.
Code Compiler Link: https://app.singhteekam.in/codecompiler/