How to remove the first character of a string in JavaScript.

In this tutorial, we will show you how remove the first character of a string using JavaScript.

To do this, we can use JavaScript’s substring method.

Take a look at the following example:

//An example JavaScript string
var str = '(T384';

//Let's remove the first character
str = str.substring(1);

//Log the result to the console
console.log(str); //result: T384

As you can see, our string contains a rounded bracket at the start of it. However, we are able to remove this by using the substring method.

The substring method does exactly what its name suggests. It returns a subset of a string.

By passing in 1 as the parameter, we are telling the function to return everything from index 1 and onward. Remember that in programming, strings and arrays usually start with a 0.

In this particular case, our “(” character is at position 0, whereas “T” is at position 1.

To sum it up, the first character in a JavaScript string will always be located at index 0.

Therefore, in order to remove that character, we must “extract” everything from index 1 onward and then overwrite the original variable with the result.

If you run the snippet above, you will see that we are left with the string “T348”.

Removing multiple characters from the start of a JavaScript string.

Similarly, we can also remove multiple occurrences of a character from the start of a string. But, in this case, we will also need to use a while loop and the charAt method.

Let’s say that we have a string such as “…ABC”.

However, we want to remove all of those full-stop characters from the beginning of the string.

//A string with dots at the start of it.
var str = '...ABC';

//While there is a dot character at position 0
while(str.charAt(0) == '.'){
    //Get the substring and then overwrite
    //the string
    str = str.substring(1);
}

In the example above, we check to see if the first character of the string is a dot / full stop. We do this by using the charAt method.

If a dot is present at position 0, we remove it and overwrite the original variable. After that, our while loop will check the string again and do the exact same thing.

This process will continue until a dot can no longer be found at position 0.

As you might have guessed, the while loop above will iterate three times before all of the characters are removed.