For all the examples in this article, let's suppose we want to remove the first character in a string that matches a comma.
Before we dive into how to do the removing part, let's do a quick overview on how we can get the first character of a string to match against a specific character:
Find If First Character of a String Matches a Specific Character
In JavaScript we can use the following two methods to check if the first character of a string matches a specific character:
str[0]str.charAt(0)
charAt(0) has better browser support with older browsers. However, str[0] has a shorter syntax and is well-supported IE-8+.
Please note that these two methods have other minor differences, which is beyond the scope of this article.
Remove First Character of a String Using substring()
By simply doing str.substring(1) we can get the entire string excluding the first character. However, if we wanted to remove the first character conditionally upon a match, say for example, if the first character was a comma, then we can do something like the following:
let str = ',foobar';
if (str.length && str[0] === ',') {
str = str.substring(1);
}
Remove First Character of a String Using slice()
Similar to substring(), str.slice(1) would return a new string with the extracted characters of a string excluding the first one. To ensure the first character is indeed the one we wish to replace, we can do a conditional check like we did for substring(). Consider for example:
let str = ',foobar';
if (str.length && str[0] === ',') {
str = s.slice(1);
}
Using Regular Expression to Find & Remove the First Character of a String:
By using a regular expression pattern with replace() we can do find and replace in one operation. Consider the following for example, to remove the first comma in a string:
const str = ',foobar'.replace(/^,/, '');
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.