How can I get the last characters of a string?
When working with JavaScript, there may be times when you need to extract the last characters of a string. Whether you want to display a specific portion of a string or perform some manipulation, there are multiple ways to achieve this. In this blog post, we will explore three different solutions to help you get the last characters of a string.
1. Using the slice() method
The slice()
method allows you to extract a portion of a string and returns a new string containing the extracted characters. To get the last characters of a string, you can pass a negative value as the starting index to the slice()
method.
const str = "Hello, World!";
const lastCharacters = str.slice(-5);
console.log(lastCharacters); // Output: World!
In the above example, the slice()
method is used with a starting index of -5, which means it will extract the last 5 characters of the string "Hello, World!"
.
2. Using the substring() method
The substring()
method is similar to the slice()
method and allows you to extract a portion of a string. However, unlike the slice()
method, the substring()
method does not accept negative indices.
const str = "Hello, World!";
const lastCharacters = str.substring(str.length - 5);
console.log(lastCharacters); // Output: World!
In the above example, the substring()
method is used with the starting index calculated as str.length - 5
. This will extract the last 5 characters of the string "Hello, World!"
.
3. Using the substr() method
The substr()
method allows you to extract a specified number of characters from a string, starting from a specified index. To get the last characters of a string, you can pass a negative value as the starting index to the substr()
method.
const str = "Hello, World!";
const lastCharacters = str.substr(-5);
console.log(lastCharacters); // Output: World!
In the above example, the substr()
method is used with a starting index of -5, which means it will extract the last 5 characters of the string "Hello, World!"
.
Now that you have learned three different ways to get the last characters of a string in JavaScript, you can choose the method that best suits your requirements. Whether it’s using slice()
, substring()
, or substr()
, you can easily extract the desired portion of a string and manipulate it as needed.
Happy coding!
Leave a Reply