JavaScript endswith() method


The endsWith() method in JavaScript is used to determine whether a string ends with a specified substring (search string). It returns a boolean value (true or false) based on whether the string concludes with the specified substring.

Syntax:

string.endsWith(searchString, length)
  • searchString: The substring you want to check for at the end of the string.
  • length (optional): An integer that specifies the length of the string to consider for the search. If provided, the search will only consider the substring from the start of the string up to the specified length. If omitted, the entire string is considered.

Return Value:

  • It returns true if the string ends with the specified searchString; otherwise, it returns false.

Example 1: Basic Usage

let fileName = "document.pdf"; let result = fileName.endsWith(".pdf"); console.log(result); // true

In this example, the string "document.pdf" indeed ends with the substring ".pdf", so endsWith() returns true.

Example 2: Case Sensitivity

The endsWith() method is case-sensitive. This means that "Hello" and "hello" are treated as different strings.

let message = "Hello, World!"; console.log(message.endsWith("world!")); // false console.log(message.endsWith("World!")); // true

Example 3: Specifying the Length

You can specify the length to limit the portion of the string that is considered for the search. The search will only look at the characters from the start of the string up to the specified length.

let sentence = "The quick brown fox jumps over the lazy dog."; console.log(sentence.endsWith("lazy dog.", 43)); // true console.log(sentence.endsWith("lazy dog.", 42)); // false (the search only considers "The quick brown fox jumps over the lazy")

Example 4: Handling Empty Strings

If you check for an empty string, the endsWith() method will always return true, as any string ends with an empty substring.

let text = "Hello, world!"; console.log(text.endsWith("")); // true

Example 5: Not Finding the Substring

If the searchString is not found at the end of the original string, the method will return false.

let url = "https://example.com/home"; console.log(url.endsWith("/about")); // false

Summary:

  • The endsWith() method checks if a string ends with a specified substring and returns true or false.
  • It is case-sensitive and can accept an optional second argument to specify the length of the string to consider.
  • The method returns true for an empty search string since every string ends with an empty substring.
  • This method is useful for validating file extensions, URL paths, and other string patterns at the end of a string.