To get the last N or 4 characters of a string, use the slice
method on the string in JavaScript. You have to pass the value as a parameter, e.g. str.slice(-4)
returns a new string containing the last 4 characters of the original string.
Get the last 4 characters of the string JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const str = 'Hello World';
const res = str.slice(-4);
console.log(res);
var txt = "Pink City"
const last4 = txt.slice(-4);
console.log(last4);
</script>
</body>
</html>
Output:
![Get last 4 characters of string JavaScript](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2022/06/Get-last-4-characters-of-string-JavaScript.jpg?resize=206%2C101&ssl=1)
You could also use the String substring method to get the last N characters of a string.
const str = 'Hello World';
const last3 = str.substring(str.length - 3); // rld
console.log(last3);
Do comment if you have any doubts or suggestions on this JS code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version