2 different JavaScript methods to remove first n characters from a string

JavaScript program to remove first n characters from a string:

In this post, we will learn how to remove the first n characters from a string in JavaScript. For example, if the string is hello and if we want to remove first two characters from the string, it will give llo. Strings are immutable. So, this program will create one new string instead of changing the original.

We can use slice and substring methods to remove any number of characters from a string. In this post, I will show you how to remove the last n characters of a string using slice and substring.

Example to remove last n characters from a string using slice:

JavaScript slice method is defined as below :

slice(start, end)

Here,

  • start is the start position in the array where slicing will start
  • end is the end position in the array where slicing should stop. This is optional.

This method returns one new string by extracting one substring from the string. In our case, we will only provide the start index. It will slice from start to end of the string.

Below is the complete program:

const str1 = "@@@Hello One !!";
const str2 = "@@!!Hello Two !!";
const str3 = "@@##%%^Hello Three !!";

console.log(str1.slice(3));
console.log(str2.slice(4));
console.log(str3.slice(7));

Here,

  • For str1, we are removing the first 3 characters
  • For str2, we are removing the first 4 characters
  • For str3, we are removing the first 7 characters

It will print:

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

Using substring():

substring is another method we can use to remove first characters from a JavaScript string. This method is defined as below:

substring is defined as below:

substring(first, second)

This method extracts one substring from a string between first and second. It includes all characters from first up to second, without including second in the new string. It returns the new substring.

second is an optional parameter and in our case, we will provide only first. It will extract the string from first to end of the string.

So, If I write the above program using substring, it looks as like below:

const str1 = "@@@Hello One !!";
const str2 = "@@!!Hello Two !!";
const str3 = "@@##%%^Hello Three !!";

console.log(str1.substring(3));
console.log(str2.substring(4));
console.log(str3.substring(7));

It will print the same output:

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

You might also like: