In JavaScript, we can remove the first character from a string easily using the String substring() method.

var newString = oldString.substring(1);

The code above will return the original string minus the first character.


Let’s say we have the following JavaScript:

var someString = "This is some example text";
var newString = someString.substring(1);

In the above code, newString will have the following value after applying the substring method to the original string:

his is some example text

We can also remove the first character from a string using the String slice() method.

var someString = "This is some example text";
var newString = someString.slice(1);

This code will provide the same results as the substring method did above.

Let’s take a look at another simple example.

Using JavaScript to Remove the First Character From a String with a Click

In this simple example, we will have a really long string to start out. We will then provide a button to let the user remove the first character from that string as many times as they want.

Here is the HTML setup:

Remove first character

First, we will populate the div #updatedString with a long string we will make up.

We will then add an onclick event to our #click-me div that will run a function we will create called removeFirstCharacter(). Our function will remove the first character of the string using the substring() method.

We will finally update the #updatedString div using the textContent property with the new string.

Here is the JavaScript code:

//Our string
var startingString = "This is a long string that we can remove the first character from as many times as we want by pressing the button below.";
  
//We will populate the div #updatedString with our string
document.getElementById("updatedString").textContent = startingString;

function removeFirstCharacter(){

  //We remove the first character of the string
  startingString = startingString.substring(1);

  //We will then update the div #updatedString with our new string
  document.getElementById("updatedString").textContent = startingString;

}

The final code and output for removing the first character from a string using JavaScript is below:

Code Output:

Remove first character

Full Code:

Remove first character
<script> var startingString = "This is a long string that we can remove the first character from as many times as we want by pressing the button below."; document.getElementById("updatedString").textContent = startingString; function removeFirstCharacter(){ startingString = startingString.substring(1); document.getElementById("updatedString").textContent = startingString; } </script>

Hopefully this article has been useful for you to learn how to use JavaScript to remove the first character from a string.

Categorized in:

JavaScript,

Last Update: February 26, 2024