Drop first n characters from a string in JavaScript
This post will discuss how to drop the first n characters from a string in JavaScript.
There are several ways to drop the first n characters from a string in JavaScript. Here are some of the most common functions, along with some examples:
1. Using slice() function
The slice() function takes one or two arguments, the start and end index of the substring to be removed, and returns a new string without that substring. We can use this function to get rid of the first n characters from a string by passing n as the start index and omitting the end index. For example, to drop the first 3 characters from a string:
|
1 2 3 4 5 6 |
let str = "Hello, World!"; let n = 3; // Use the slice function to drop the first n characters str = str.slice(n); console.log(str); // Output: "lo, World!" |
2. Using substring() function
The substring() function is similar to the slice() function, and returns a portion of a string based on specified start and end indices. We can also omit the second argument if we want to keep all characters from the start index to the end of the string. For example, to drop the first 3 characters from a string:
|
1 2 3 4 5 6 |
let str = "Hello, World!"; let n = 3; // Use the substring function to drop the first n characters str = str.substring(n); console.log(str); // Output: "lo, World!" |
3. Using replace() function
The replace() function looks for a specific pattern in a string and changes it with a new substring. We can apply this function to delete the first n characters from a string by using a regular expression that matches any character n times at the start of the string and changing it with an empty string (""). For example, the following code removes the first three characters from the string by matching any character (.) that occurs at the start of the string (^) for three times ({3}).
|
1 2 3 4 5 6 |
let str = "Hello, World!"; let n = 3; // Use the replace function with a regular expression to drop the first n characters str = str.replace(new RegExp(`^.{${n}}`), ""); console.log(str); // Output: "lo, World!" |
That’s all about dropping the first n characters from a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)