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
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
4. Native endsWith() Method
In ES6 and modern browsers, endsWith() is widely available as a native string method.
const str = "mystring#"; str.endsWith("#"); // true
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; }
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!