Skip to content
Home » How to Extract the Last 3 Characters from a String in JavaScript

How to Extract the Last 3 Characters from a String in JavaScript

In this tutorial, we will learn how to extract the last three characters from a string using JavaScript. This can be useful in situations where you need to manipulate or analyze a specific portion of a string. By using the built-in “slice” method, we can easily achieve this task. Let’s dive into the code and see an example.

Code

var member = "my name is Afia";

var last3 = member.slice(-3);

alert(last3); // "fia"

Code Explanation

The code snippet provided demonstrates how to extract the last three characters from the string “my name is Afia”.

javascript
var member = "my name is Afia";
var last3 = member.slice(-3);
alert(last3); // "fia"

In the above code, we declare a variable named “member” and assign it the value of the string “my name is Afia”.

The slice() method is then used on the “member” string, with the parameter set to “-3”. The negative value indicates that we want to slice the string starting from the third character from the end.

Finally, the resulting string, which consists of the last three characters, is stored in the variable “last3”. The alert() method is used to display the extracted characters, which in this case is “fia”.

Conclusion

In this tutorial, we have learned how to extract the last three characters from a string in JavaScript. The `slice()` method provides an easy way to accomplish this task, by specifying a negative parameter to indicate the start position from the end of the string. By understanding and utilizing this method, you can manipulate and extract specific portions of strings in your JavaScript programs.

Also checkout the following codes.


“How to Retrieve Data from an API using Fetch in JavaScript”
Program to Create an Anonymous JavaScript Function