Skip to content

Remove the last 2 character from the string JavaScript | Code

  • by

Use slice() method with 0 for the start index and -2 for the end index as parameters to Remove the last 2 character from the string in JavaScript.

str.slice(0, -2); 

This method return a new string containing the extracted section of the original string.

Note: Passing an end index parameter of -2 and str.length - 2 is the same.

Remove the last 2 characters from the string JavaScript

Simple example code.

<!DOCTYPE html>
<html lang="en">
<body>
  <script>
   const str = 'Hello io';

   const res = str.slice(0, -2);
   console.log(res); 

   console.log("Original", str)
 </script>
</body>
</html>

Output:

Remove the last 2 character from the string JavaScript

Alternative method

You can use substring() method on the string to remove the last 2 characters from a string by passing it 0 for the start index and str.length - 1 for the end index as parameters.

const str = 'one two';

const res = str.substring(0, str.length - 2);
console.log(res); // one t

More examples

let str = "12345.00";
str = str.substring(0, str.length - 2);
console.log(str); //12345.

Do comment if you have any doubts or suggestions on this JS remove char 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 *