How to Get the Last Characters of a String in JavaScript

Strings are an essential data type in programming and JavaScript is no exception.

As a language, JavaScript provides several methods to manipulate strings and one such method is getting the last characters of a string.

In this Javascript tutorial, we will discuss various methods to get the last characters of a string in JavaScript.


Substring

The substring method in JavaScript is used to extract a portion of a string.

In this method, we can specify the starting and ending index of the string from which we want to extract the characters.

To get the last characters of a string, we can specify the length of the string minus the number of characters we want to retrieve as the starting index and the length of the string as the ending index.

Example:

let str = "Hello World!";
let lastThree = str.substring(str.length - 3, str.length);
console.log(lastThree);  // "rld"

Slice

The slice method in JavaScript is used to extract a portion of a string and is similar to the substring method.

However, the slice method allows us to specify negative index values, making it easier to retrieve the last characters of a string.

Example:

let str = "Hello World!";
let lastThree = str.slice(-3);
console.log(lastThree);  // "rld"

Substr

The substr method in JavaScript is used to extract a portion of a string, similar to the substring method.

In this method, we specify the starting index and the number of characters we want to retrieve.

To get the last characters of a string, we can specify the length of the string minus the number of characters we want to retrieve as the starting index and the number of characters we want to retrieve as the second argument.

Example:

let str = "Hello World!";
let lastThree = str.substr(str.length - 3, 3);
console.log(lastThree);  // "rld"

CharAt

The charAt method in JavaScript is used to retrieve a single character from a string, based on its index.

To get the last character of a string, we can specify the length of the string minus one as the index.

To get more than one character, we can use a loop and decrement the index by one each time.

Example:

let str = "Hello World!";
let lastThree = "";
for (let i = 2; i >= 0; i--) {
  lastThree = str.charAt(str.length - i - 1) + lastThree;
}
console.log(lastThree);  // "rld"

Conclusion

In conclusion, there are several methods to get the last characters of a string in JavaScript, including the substring, slice, substr, and charAt methods.

Choose the method that best suits your needs, based on the type of data you are working with and the results you want to achieve.

Each method has its own advantages and disadvantages, so be sure to choose the one that works best for your specific use case.