Skip to content

Get last 4 characters of string JavaScript | Example code

  • by

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 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

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

Leave a Reply

Your email address will not be published. Required fields are marked *