Home > Web Front-end > JS Tutorial > How to Determine if a String Ends with a Specific Character in JavaScript?

How to Determine if a String Ends with a Specific Character in JavaScript?

DDD
Release: 2024-11-21 01:17:12
Original
792 people have browsed it

How to Determine if a String Ends with a Specific Character in JavaScript?

endsWith() in JavaScript

Determining if a string concludes with a specific character is a common task in JavaScript. To achieve this, we have a few options:

1. Does JavaScript Have an endsWith() Method?

Unfortunately, JavaScript lacked an in-built endsWith() method as of 2010. However, in modern browsers, endsWith() has been incorporated as a native method.

2. Custom endsWith() Implementation:

Prior to endsWith(), a popular approach involved calculating the string's length, extracting the last character, and comparing it to the desired character.

const str = "mystring#";
const lastChar = str[str.length - 1];
lastChar === "#"; // true
Copy after login

3. Alternative Solution Using indexOf():

Using indexOf(), we can locate the character's position within the string. If the character is present, the position will be a non-negative number; otherwise, it will be -1.

const str = "mystring#";
str.indexOf("#", str.length - 1) !== -1; // true
Copy after login

4. Native endsWith() Method

In ES6 and modern browsers, endsWith() is widely available as a native string method.

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

5. Cross-Browser Compatibility

For cross-browser compatibility, we recommend using the following standalone function:

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

Conclusion:

Depending on the JavaScript version and browser support, you can utilize the native endsWith() method or implement your own using alternative methods like indexOf().

The above is the detailed content of How to Determine if a String Ends with a Specific Character in JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template