How to get the last character of a string?
To access the last character of a string, use str[str.length - 1]
.
For a more concise solution, try str.slice(-1)
.
Different approaches and considerations
Slice into it
The slice()
method is a neat solution for retrieving the last character:
This simple and readable method is the modern preference for string manipulation operations, always picking up the perfect slice of your string.
CharAt vs. Bracket notation
Using charAt
For readabilty-oriented code, charAt()
is just what you need:
charAt()
nicely returns an empty string if the provided index is out of range, keeping your code error-free.
Bracket scenario
Or use bracket notation to get that last character:
While bracket notation is succinct and commonly used, aware yourself of its performance on larger strings.
Testing the string with endsWith
To check whether a string ends with a specific character use endsWith()
:
endsWith()
gives you a data-loaded boolean response, no extraction or interaction needed!
Performance check: charAt vs. Bracket notation
Choosing between charAt()
and bracket notation also involves considering performance. charAt()
typically ends up rapid, especially for older browsers. It's also more suitable when working with special non-BMP characters.
Dealing with edge cases
For handling empty strings and to ensure fail-proof operations:
A ternary operation like this ensures you avoid exceptions and handle strings of all sizes.
Using in template literals
In ES6, you can directly use these within your template literals:
Compatibility check
While slice()
, charAt()
and brackets are widely supported in modern environments, always perform a compatibility check if you're working with legacy systems.
Was this article helpful?