JavaScript: Remove the first character of a string.

This is a tutorial on how to remove the first character of a string using JavaScript. To do this, we can using JavaScript’s substring method.

Take a look at the following example.

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

The substring method does exactly what the 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.

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.

Facebook Comments