Explain Codes LogoExplain Codes Logo

How can I get last characters of a string

javascript
negative-indexing
string-extraction
performance-optimization
Alex KataevbyAlex Kataev·Nov 5, 2024
TLDR

Get the last n characters of any string with the .slice(-n) method:

let str = 'ExampleString'; let lastN = str.slice(-5); // Returns 'tring'

If n is larger than the string's length, you'll get the entire string — no surprise guests at your string party!

Grabbing specific end characters

Use negative indexing with .slice() to extract a specific number of characters from the end of a string. Looking for the last five characters? Here's how:

let lastFive = str.slice(-5); // 'tring' encore!

If n is larger than the string's length, fear not! .slice(-n) will party on and return the entire string without skipping a beat.

Give last characters a stage

Sometimes, the stage demands a character that shows up after a particular delimiter like an underscore. For those encore moments, use .split().pop():

let divaString = 'underscore_centric'; let lastAct = divaString.split('_').pop(); // The star of the show: 'centric'

Other methods for the show

Employ .substring() with a calculated start index if .slice() feels too backstage. And if you prefer specifying the number of characters to extract, .substr() used to be your go-to guy, but it's now deprecated:

// .substring() in action let position = str.length - 5; let lastFiveViaSubstring = str.substring(position); // Just like .slice(-5) // Do remember, .substr() has left the building 🕺 let lastFiveViaSubstr = str.substr(-5); // Please, don't try this at home!

Avoid stepping on the banana peel

Dealing with edge cases is like walking through a dark room full of banana peels. Here's how to get to the other side without slipping:

  • String shorter than n: .slice(-n) returns the full string, no fuss. It's like the lights suddenly turned on.
  • Empty string: You get an empty string in return. No banana peels here. Move along!
  • Non-string input: Better turn on the lights and convert to string first. That way, the banana peels have nowhere to hide.

Performance: Off Broadway

For Broadway-sized strings, where performance is crucial, keep in mind that .slice() and .substring() have similar performance on most JavaScript engines. But if every millisecond counts, it's worth running your own benchmarks based on your specific use case.

Diving into string methods

While it's clear that .slice() and .substr() are okay with negative indexes, .substring() isn't. Furthermore, .substring() expects the second parameter as an end index, whereas .substr() treats it as the length to extract:

// substring: specify the start and end let subStrExample = str.substring(2, 5); // "ample" // substr: specify the start and length let substrExample = str.substr(2, 5); // "ampleS" (S for surprise!)

Exploring the Theatre of 'Stringlandia'

Think of each string extraction method as a unique stage performance which can make or break the show:

Curtain rising with the substring method

let sampleScript = "CurtainCall"; let grandFinale = sampleScript.substring(sampleScript.length - 4); // "Call"

On thin Ice... Not!

let understudy = "Extra"; let roleLength = 10; // Oh No! // No worries, good old .slice() has your back! let perhapsMoreThanExtra = understudy.slice(-roleLength); // "Extra"

The Unexpected Character

let oneManShow = "Monologue"; let surpriseCharacter = oneManShow.substr(6); // "ogue" (Who's this 'ogue' fella?)