2 different JavaScript program to remove last n characters from a string

JavaScript program to remove last n characters from a string:

In this post, we will learn how to remove the last n characters from a string in JavaScript. JavaScript provides slice and substring methods that can be used to remove the last characters from a string.

For example, if the string is hello and if we are removing last 3 characters from the string it will print he.

Remove last n characters from a string using slice() in JavaScript:

slice method is defined as below:

slice(first, second)

Here, first is the index of the first character in the string and second is the index of the last character of that string. It extracts one substring from the given string in the range first and second, including character at index first and upto character at index second excluding the character at index second.

In our case the value of first is 0 and for second, we will use negative index. If we give -1 as the value of second, it will remove the last character of the string. Similarly, for -n, it will remove all n characters from the end of the string.

Let’s take a look at the below example:

const str1 = "Hello One !!***";
const str2 = "Hello Two !!*";
const str3 = "Hello Three !!** ** **";

console.log(str1.slice(0,-3));
console.log(str2.slice(0,-1));
console.log(str3.slice(0,-8));

It will print:

Hello One !!
Hello Two !!
Hello Three !!

Using negative index, we removed the last characters from the string.

Remove last n characters from a string using substring() in JavaScript:

substring is similar to slice. This method is defined as below:

substring(first, second)

Similar to slice, it returns one string extracting from first to second index, including the character at index first and up to character second, excluding character at second index.

We can use negative index for second similar to slice.

We need to just replace slice with substring in the above program to get similar result.

const str1 = "Hello One !!***";
const str2 = "Hello Two !!*";
const str3 = "Hello Three !!** ** **";

console.log(str1.slice(0,-3));
console.log(str2.slice(0,-1));
console.log(str3.slice(0,-8));

It will print:

Hello One !!
Hello Two !!
Hello Three !!

You might also like: