Home > Web Front-end > JS Tutorial > body text

How to Check if a JavaScript String Ends With a Specific Character?

Susan Sarandon
Release: 2024-11-15 21:35:03
Original
186 people have browsed it

How to Check if a JavaScript String Ends With a Specific Character?

endsWith() Method for JavaScript: Checking String Endings

In JavaScript, determining whether a string ends with a particular character is a common need. While a variety of approaches exist, the most efficient and cross-browser compatible method is to utilize the endsWith() function.

Built-in endsWith() Method

Unfortunately, as of the writing of the original post in 2010, JavaScript did not have a native endsWith() method. However, since ECMA6, this functionality has been added to the core language. To use it, simply call endsWith() on the string object, passing in the character or substring you want to check for:

const str = "mystring#";
console.log(str.endsWith("#")); // Output: true
Copy after login

Custom Implementation

If you are unable to use the native endsWith() method, a custom implementation can be created:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
Copy after login

This function uses the indexOf() method to search for the suffix in the string, starting from a position that skips the last suffix.length characters. If the suffix is found at the end, the return value will be greater than or equal to 0, indicating that the string ends with the specified character.

Other Approaches

Other less efficient methods include:

  • Substring comparison: Comparing the last suffix.length characters of the string to the suffix.
  • Regex search: Using a regular expression to check for the suffix at the end of the string.

In conclusion, the native endsWith() method is the preferred way to check if a string ends with a particular character in JavaScript. For older browser compatibility, a custom implementation can be used.

The above is the detailed content of How to Check if a JavaScript String Ends With a Specific Character?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template