Home >Web Front-end >JS Tutorial >How to Check if a String Ends with a Character in JavaScript?
endsWith in JavaScript: A Comprehensive Guide
Checking if a string ends with a specific character is a common task in JavaScript programming. While JavaScript does not provide a native endsWith() method, there are several effective ways to achieve this functionality.
Option 1: Using indexOf()
The indexOf() method can be used to locate the first occurrence of a substring within a string. By passing the substring and the starting position as arguments, indexOf() searches for the substring starting from the specified position. To check if a string ends with a character, you can pass the character as the substring and the length of the string minus the length of the character as the starting position.
For example:
var str = "mystring#"; var char = "#"; var index = str.indexOf(char, str.length - char.length); if (index !== -1) { console.log("String ends with the character."); }
Option 2: Using substr()
The substr() method can extract a substring from a string based on a specified starting position and length. To check if a string ends with a character, you can extract the last character using substr() and compare it to the desired character.
For example:
var str = "mystring#"; var char = "#"; var lastChar = str.substr(str.length - char.length, char.length); if (lastChar === char) { console.log("String ends with the character."); }
Option 3: Using a Regular Expression
Regular expressions provide a powerful tool for pattern matching in text strings. To check if a string ends with a character, you can create a regular expression with the character preceded by a caret (^) to indicate the end of the string.
For example:
var str = "mystring#"; var char = "#"; var regex = new RegExp(char + "$"); if (regex.test(str)) { console.log("String ends with the character."); }
ES6 Support
In ES6 (ECMAScript 2015), the native String.prototype.endsWith() method was introduced to simplify the process of checking if a string ends with a character.
For example:
var str = "mystring#"; var char = "#"; if (str.endsWith(char)) { console.log("String ends with the character."); }
Conclusion
While there are multiple ways to check if a string ends with a character in JavaScript, the native endsWith() method from ES6 is the most concise and efficient option. However, if you need to support older browsers, implementing one of the alternative approaches discussed above is necessary.
The above is the detailed content of How to Check if a String Ends with a Character in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!