Does your project involve string manipulation? Or perhaps, do you have strings where you need to get rid of the initial character? This guide will assist you in simplifying such tasks, making your coding journey smoother and more efficient.
- By slice() method
- By substring() method
- By using array destructuring and join() method
Let’s explore each…
#1 – By slice() method
The slice() method extracts a section of a string and returns it as a new string. In our case, we use it to remove the first character by starting the slice from the second character (index 1). For instance, if we have a string “Hello”, after applying the method, we will get “ello”.
var str = "Hello"; var newStr = str.slice(1);
How it works
- First, we declare a variable ‘str’ and assign it the string “Hello”.
- Next, we call the slice() method on ‘str’ with the starting index set as 1, meaning we want to start our new string from the second character of ‘str’.
- The slice() method then returns a new string starting from the second character to the end of ‘str’. This new string is stored in another variable ‘newStr’.
- As a result, ‘newStr’ now holds the string “ello”, which is the original string “Hello” but without the first character.
#2 – By substring() method
Let’s consider an example: If we start with the string “Hello, World!” and want to remove the first character, the resulting string should be “ello, World!”. We can achieve this using the substring() method as follows:
var str = "Hello, World!"; var newStr = str.substring(1);
How it works
- First, a variable ‘str’ is defined with the original string “Hello, World!”.
- Then, a new variable ‘newStr’ is defined. The substring() method is called on the original string ‘str’ with argument ‘1’.
- Thus, the first character of the original string is effectively removed in the new string ‘newStr’.
#3 – By using array destructuring and join() method
let str = "Hello World"; let [, ...chars] = str; let result = chars.join('');
How it works
Let’s break this down:
- First, we declare the string from which we want to remove the first character: let str = “Hello World”;
- Next, we use array destructuring to separate the first character from the rest of the string: let [, …chars] = str;. Here, the , skips the first character, and …chars collects the rest of the characters into an array.
- Finally, we use the join(”) method, which combines all the elements of the chars array into a string, effectively creating a new string without the first character: let result = chars.join(”);