You can use the slice() method to get the last N characters of a string in JavaScript, passing -n as a negative start index. For example, str.slice(-2) returns a new string containing the last 2 characters of the string.

const str = 'JavaScript'

const last2 = str.slice(-2)
console.log(last2) // pt

const last4 = str.slice(-4)
console.log(last4) // ript

const last6 = str.slice(-6)
console.log(last6) // Script

The slice() method takes the start and end indexes as parameters and returns a new string containing a slice of the original string. It returns the extracted part as a new string and does not change the original string.

When you pass only a start index, the slice() method returns the entire part of the string after the start index.

When you pass a negative start index to slice(), it counts backward from the last string character to find an equivalent index. So passing -n to slice() is equivalent to str.length - n, as shown below:

const str = 'JavaScript'

const last4 = str.slice(-4)
console.log(last4) // ript

const last4Again = str.slice(str.length - 4)
console.log(last4Again) // ript

If you provide a start index greater than the string's length, the slice() method does not throw an error. Instead, it returns a copy of the original string:

const str = 'JavaScript'

const last20 = str.slice(-20)
console.log(last20) // JavaScript

In the above example, we tried to get the last 20 characters of the string by passing -20 as a negative start index, but the string 'JavaScript' contains only 13 characters. Hence, slice() returns the entire string.

Alternatively, you could also use the substring() method to get the last N characters of a string in JavaScript:

const str = 'JavaScript'

const last6 = str.substring(str.length - 6)
console.log(last6) // Script

The substring() method works similarly to slice() and returns a new string containing part of the original string specified using start and end indexes.

However, unlike slice(), the substring() method uses 0 as a start index if a negative number is passed as an argument:

const str = 'JavaScript'

const last4 = str.substring(-4)
console.log(last4) // JavaScript

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.