How to remove the first 2 characters from a string in JavaScript

Remove the First 2 Characters from a String in JavaScript

If you need to learn how to remove the first 2 characters from a string in JavaScript, follow this article to understand and practice how to do it.

Remove the first 2 characters from a string in JavaScript

Using string.substring() method

The string.substring() method extracts a substring between the two specified indices in the parent string.

Syntax:

string.substring(start, end)

Parameters:

  • start: is the index of the first character from which you want to start the extraction.
  • end: is the index of the last character you want to end the extraction.

Suppose we pass a single numeric value into the function. In that case, the program will recognize it as a start parameter, so you can use this method to remove the first two characters of the string by passing it parameter equals “2”. Please pay attention to the code below to understand how it works.

Code:

var string = "Hi Welcome to LearnShareIT";
var newString = string.substring(2);
console.log(newString);

Output:

" Welcome to LearnShareIT"

With only one numeric value passed, the end parameter is automatically defined by the function as the last index of the string, which means we will get a string starting from the second value to the end of the string. This is precisely what we need to do in this article. Follow the next steps to know more ways to do this topic.

Using slice() method

Or you can also use the slice() function with the input string and pass it a parameter of two, which can return a value similar to using a substring. All we need to do is replacing the substring() function with the slice() function.

Code:

var string = "Hi Welcome to LearnShareIT";
var newString = string.slice(2);
console.log(newString);

Both of these functions are widely used by Javascript users to work with strings, but not everyone understands these two methods well and masters how it works. With the slice() method, you can also pass it a negative value so that different substrings can be obtained in exceptional cases. If the start is a negative number, slice() will position the count from the end of the string, just like substring(). In the case of counting from the end of the string, but the start position still exceeds the end position, it will be like the case start > stop. Good luck with these two methods.

Summary

In summary, with both methods mentioned in the article, you can remove the first 2 characters from a string in JavaScript. You should learn more about these methods to work with strings flexibly.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *