W3docs

How to Get the Last Characters of a String

Read and learn several easy and simple methods you can use for retrieving the last characters of a JavaScript string. Choose the best method for your case.

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

The recommended approach is to use the JavaScript string <kbd class="highlighted">.slice()</kbd> method combined with the length property.

JavaScript slice method

javascript— editable

The <kbd class="highlighted">.slice()</kbd> method extracts parts of a string and returns the extracted parts in a new string. It is the preferred method for getting the last characters as it provides cross-browser compatibility and is not deprecated.

Another method is <kbd class="highlighted">.substr()</kbd>, though it is deprecated in modern JavaScript. For a similar non-deprecated alternative, use <kbd class="highlighted">.substring()</kbd>.

JavaScript substr method

javascript— editable

The <kbd class="highlighted">substr()</kbd> method returns a section of the string, starting at the specified index and continuing to a given number of characters afterward.

Strings

Strings are used to store and manipulate text in JavaScript. There is no 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 <kbd class="highlighted">str.length()</kbd> instead of just str.length, it will not work.