Explain Codes LogoExplain Codes Logo

How to get the last character of a string?

javascript
string-manipulation
slice-method
performance
Anton ShumikhinbyAnton Shumikhin·Oct 8, 2024
TLDR

To access the last character of a string, use str[str.length - 1].

let str = "Hello"; let lastChar = str[str.length - 1]; // "o" // Easy peasy, lemon squeezy!

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:

let lastChar = str.slice(-1); // "o" // Slice it like a pizza, always gets you the best bite!

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:

let lastChar = str.charAt(str.length - 1); // "o" // charAt: like your delivery guy, shows up with the right char!

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:

let lastChar = str[str.length - 1]; // "o" // Just like getting the last chips from the packet!

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():

let endsWithX = str.endsWith("x"); // false // Does it end with "x"? Nah, false alarm.

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:

let lastChar = str.length > 0 ? str.slice(-1) : null; // No more last minute panics, even when train's empty!

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:

let template = `The last character is ${str.slice(-1)}.`; // ES6: incorporating the cool kid in block!

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.