How to Delete the First Character of a String in JavaScript

String manipulation is a crucial aspect of programming and is widely used in web development, data processing, and other areas.

Understanding the methods to manipulate strings is essential for every JavaScript developer.

In this Javascript tutorial, we will be discussing the various methods to remove the first character from a string in JavaScript.


Using String.slice()

The slice() method in JavaScript is used to extract a part of a string and return a new string.

This method accepts two arguments, start and end, where start is the index of the first character to extract and end is the index of the last character to extract.

To remove the first character of a string, we can use the slice() method by passing the second argument as 1.

Example:

let str = "Hello World";
let newStr = str.slice(1);
console.log(newStr);  // Output: "ello World"

Using String.substr()

The substr() method in JavaScript is used to extract a part of a string and return a new string.

This method accepts two arguments, start and length, where start is the index of the first character to extract and length is the number of characters to extract.

To remove the first character of a string, we can use the substr() method by passing the second argument as 0.

Example:

let str = "Hello World";
let newStr = str.substr(1);
console.log(newStr);  // Output: "ello World"

Using String.replace()

The replace() method in JavaScript is used to replace a specified value in a string with a new value.

This method can be used to remove the first character of a string by replacing the first character with an empty string.

Example:

let str = "Hello World";
let newStr = str.replace(str[0], "");
console.log(newStr);  // Output: "ello World"

Using Array.join()

In JavaScript, a string can be converted to an array using the split() method and an array can be converted back to a string using the join() method.

To remove the first character of a string, we can split the string into an array, shift the first element from the array, and join the array back to form a new string.

Example:

let str = "Hello World";
let charArr = str.split("");
charArr.shift();
let newStr = charArr.join("");
console.log(newStr);  // Output: "ello World"

Conclusion

In this tutorial, we have discussed four methods to remove the first character of a string in JavaScript.

The slice() and substr() methods are simple and straightforward, while the replace() method requires a bit more understanding of string manipulation.

The join() method, although a bit longer, is an efficient way to remove the first character of a string.

Choosing the right method depends on the requirement and personal preference of the developer.