Removing the first character from a string - JavaScript

Posted on February 10, 2021

When you need to remove a character from a string, you can use the substring() method. The substring() method returns a part of the string from the start and end indexes that you specified as its arguments:

String.substring(start, end);

The start index is required by the method, while the end index is optional. When you omit the end index, the method will not cut the string before the end.

When you need to remove only the first character, you can call .substring(1) on your string. Here’s an example:

let str = "hello there";
let res = str.substring(1);
console.log(res); // "ello there"

The res variable above will exclude the first character h from the str variable.

Removing only certain character

At times, you may want to remove the first character of a string only if it’s a certain character.

For example, let’s say you have a string representing your website’s URL:

let url = "/users";

If you only want to remove the forward slash (/) character, you can check the character using .charAt(0) method:

let url = "/users";
if (url.charAt(0) === "/") {
  url = url.substring(1);
console.log(url); // "users"

The charAt() method allows you to check on the individual characters of a string through its index. You can also create a reusable function from this as follows:

let url = "/users";
let res = removeFirstChar(url);

console.log(res); // "users"

function removeFirstChar(str){
  if(str.charAt(0) === "/"){
    str = str.substring(1);
  return str;

You can modify the function to suit your need.

More on JavaScript:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more