How to Get the Last Characters of a String

There are several methods used to get the last character of a string. In this tutorial you can find the simple solution for your case.

You can use the Javascript string method .substr() combined with the length property.

w3docs logo Javascript substr method
let id = "example_String1"; let lastSeven = id.substr(id.length - 7); // "String1" console.log(lastSeven); let lastChar = id.substr(id.length - 1); // "1" console.log(lastChar);

The substr() method returns a section of the string, starting at the specified index and continuing to a given number of characters afterward.

Another method is .slice() which is used to get the last characters of the string:

w3docs logo Javascript slice method
const id = "example_String1"; console.log(id.slice(id.length - 7)); // "String1" console.log(id.slice(id.length - 1)); // "1"

The .slice() method takes out parts of a string and returns the extracted parts in a new string. This method is a better method to use for getting the last characters as it provides cross-browser compatibility.

Strings

The strings are used to store and manipulate text in JavaScript. There is no any separate type for a single character. The string's internal format is always UTF-16. A string represents zero or more characters that are written inside quotes. The length property is used to find the length of a string.

Typing the property correctly is very important. If you mistype it by calling str.length() instead of just str.length, it will not work.