How to Remove Last Character from a string in JavaScript

featured Image

In this article, we will learn how to remove last character from a string in JavaScript.

Here we will be using two in-built JavaScript methods to remove the last character from a string easily.

We will be using slice() and substring() method to slice or trim off the last character from a string.

Method 1 : Using slice() in JavaScript

The slice() method helps us to remove or trim off a character from a string at a specific index. It do not change or modify the original string.

Syntax:

String.slice(start,end)

I have a start index and end index to specific which part of the string you want to extract.

Example:

var str = "Hello World";
var newStr = str.slice(0, -1);

console.log(newStr)

Output:

Hello Worl

Here the starting value is 0 and the end is -1, because a negative index indicate an offset from the end of the string.

The negative index let us to extract / remove character from the end of the string.

If you give -2, it will remove the last two characters from the end of the given string.

Method 2 : Using substring() function

The substring() method in JavaScript remove the characters between two given points: startIndex and endIndex(excluding) and return us a sub-string.

It does not change or modify the original string.

Syntax:

String.substring(indexStart, indexEnd)

IMPORTANT : The character in the startIndex is always included and the character in the endIndex is excluded while extracting the string.

Example:

var str = "Hello World";
var newStr = str.substring(0, str.length-1);

console.log(newStr)

Output:

Hello Worl

Here the start index is 0 and the end index is str.length-1, and anything between these two points is the extracted string.


Related Topics:

Remove First And Last Element From An Array In JavaScript

Capitalize First Letter Of A String In JavaScript

How to Remove Character From A String.

Replace all occurrences of a string in JavaScript

How to split string after a specific character in JavaScript

Split a String into chunks of N character into an array in JavaScript

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more