Explain Codes LogoExplain Codes Logo

How to select the last two characters of a string

javascript
slice-method
string-manipulation
javascript-utility
Anton ShumikhinbyAnton Shumikhin·Jan 1, 2025
TLDR

To swiftly get the last two characters of a string, use this quick trick with the slice(-2) method:

let lastTwoChars = "stackoverflow".slice(-2); console.log(lastTwoChars); // "ow"

A closer look at slice(-2)

Here's a slice of how JavaScript's slice() works. In this instance, -2 tells JavaScript to breezily start two steps back from the string's end until it reaches the end. Voilà! You get the last two characters.

The case for short strings

When dealing with strings shorter than two characters, the magnificent slice(-2) will just return the entire string. It's like asking for two cupcakes when there's only one left - you get what's available.

let short = "N".slice(-2); // "Single cupcake, please!" - Ultimatum for strings with less than 2 characters console.log(short); // "N"

Null or undefined strings? No worries!

In the wilderness of coding, frequent encounters with null or undefined strings are as common as finding bugs in a garden. The slice() method is equipped to adeptly handle these.

let ghostString; // GhostBusters, hold on a second; Optional chaining here to rescue console.log(ghostString?.slice(-2) ?? "(whistles) Ghost string!");

Advantages of slice()

There's an armory of methods to manipulate strings in JavaScript, like substr() and substring(). Among them, slice() stands tall as the go-to method due to its versatility and simplicity.

Renovating older patterns

Inheritors of legacy codebases, don't fret. Here's how you can trade up from substr() to slice():

// The old king: substr() let theOldWay = "stackoverflow".substr(-2); console.log(theOldWay); // "ow" // The new way: slice(), long live the king! let theNewWay = "stackoverflow".slice(-2); console.log(theNewWay); // "ow"

Why slice trumps substr

The slice() method surpasses substr() not just in versatility, it reflects the consistency of behaviour shared by arrays and strings. It's the way to go for clarity and simplicity!

Handling diverse scenarios

Among its repertoire of tricks, slice() can adapt to a gamut of situations, coming out unscathed:

Empty strings

An empty string? More like an invisible cloak! But slice() ain't fooled!

let invisibleString = "".slice(-2); console.log(invisibleString); // ""

Shorter strings

Less than two characters in a string and slice() will smartly return what's available. No errors, no fuss!

let miniString = "Just kidding, it's -> X".slice(-2); console.log(miniString); // "-> X"

Large negative indices

Supplying larger negative index to slice() gives out the whole string. Now, that's generosity!

let wholeShebang = "Hasta la vista, Baby!".slice(-30); console.log(wholeShebang); // "Hasta la vista, Baby!"