Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if string ends with desired character in JavaScript
In JavaScript, you can check if a string ends with a specific character using several built-in methods. The most common approaches are using endsWith(), charAt(), or bracket notation.
Understanding the Problem
We need to determine if a given string ends with a specific character. For example, checking if "Hello World!" ends with "!" should return true, while checking if "Hello World." ends with "!" should return false.
Using endsWith() Method (Recommended)
The endsWith() method is the most straightforward approach:
const str1 = "Hello, Tutorials Point!";
const str2 = "Hello, World.";
const desiredChar = "!";
console.log(str1.endsWith(desiredChar)); // true
console.log(str2.endsWith(desiredChar)); // false
// You can also check for multiple characters
console.log("JavaScript".endsWith("Script")); // true
console.log("JavaScript".endsWith("Java")); // false
true false true false
Using charAt() Method
This method extracts the last character using charAt() and compares it:
function endsWithChar(str, character) {
const lastChar = str.charAt(str.length - 1);
return lastChar === character;
}
const inputStr = "Hello, Tutorials Point!";
const inputStr1 = "Hello, World.";
const desiredChar = "!";
console.log(endsWithChar(inputStr, desiredChar)); // true
console.log(endsWithChar(inputStr1, desiredChar)); // false
true false
Using Bracket Notation
You can also access the last character using bracket notation:
function endsWithCharBracket(str, character) {
return str[str.length - 1] === character;
}
const text = "Programming";
console.log(endsWithCharBracket(text, "g")); // true
console.log(endsWithCharBracket(text, "m")); // false
true false
Comparison of Methods
| Method | Multi-character Support | Readability | Browser Support |
|---|---|---|---|
endsWith() |
Yes | High | ES6+ |
charAt() |
No | Medium | All browsers |
| Bracket notation | No | Medium | All browsers |
Edge Cases
Handle empty strings and special cases:
function safeEndsWithChar(str, character) {
if (!str || str.length === 0) {
return false;
}
return str.endsWith(character);
}
console.log(safeEndsWithChar("", "!")); // false
console.log(safeEndsWithChar("!", "!")); // true
console.log(safeEndsWithChar("Hello!", "!")); // true
false true true
Time Complexity
All methods have O(1) time complexity for single character checks, as they only access the last character of the string without iterating through the entire string.
Conclusion
Use endsWith() for modern applications as it's more readable and supports multi-character strings. For single characters in legacy environments, charAt() or bracket notation work effectively.
