2 Methods to Remove Last Character from String in JavaScript
Abstract: // Remove last character of stringstr = str.substring(0// Print result stringconsole.log(str) Remove last character of string with substring functionM
Question: How do I remove the last character from a string in JavaScript or Node.js script?
This tutorial describes 2 methods to remove the last character from a string in JavaScript programming language. You can use any one of the following methods as per the requirements.
Method 1 – Using substring() functionUse the substring() function to remove the last character from a string in JavaScript. This function returns the part of the string between the start and end indexes, or to the end of the string.
Syntax:
str.substring(0, str.length - 1);1str.substring(0, str.length - 1);Example:
// Initialize variable with string var str = "Hello TecAdmin!"; // Remove last character of string str = str.substring(0, str.length - 1); // Print result string console.log(str)12345678// Initialize variable with stringvar str = "Hello TecAdmin!"; // Remove last character of stringstr = str.substring(0, str.length - 1); // Print result stringconsole.log(str) Remove last character of string with substring functionMethod 2 – Using slice() functionUse the slice() function to remove the last character from any string in JavaScript. This function extracts a part of any string and return as new string. When you can store in a variable.
Syntax:
str.slice(0, -1);1str.slice(0, -1);Example:
// Initialize variable with string var str = "Hello TecAdmin!"; // Remove last character of string str = str.slice(0, -1); // Print result string console.log(str)12345678// Initialize variable with stringvar str = "Hello TecAdmin!"; // Remove last character of stringstr = str.slice(0, -1); // Print result stringconsole.log(str) Remove last character of string with javascript slice functionWrap UpIn this tutorial, you have learned about removing the last character of a sting in JavaScript. We used substring() and slice() functions to alter a string.