Reputation: 39
Hello community: I have a quick question as I am still familiarizing myself with regex. My Question is: How do i replace/delete all BUT the first character in a string in JavaScript?
Sample: If my string is "apple" and I would only want "a".
Upvotes: 3
Views: 3358
Reputation: 241198
You don't need regular expressions to remove all but the first character(s) in a string.
Use the .slice()
method:
'apple'.slice(0, 1);
// 'a'
You can also just access the first character using the .charAt()
method:
'apple'.charAt(0);
// 'a'
If you want to use the .replace()
method, then you could use the following:
'apple'.replace(/(^.).*/, '$1');
// 'a'
.
character matches any character.(^.)
is a capture group that will capture the first character.*
will match all the following characters (*
means any character will be matched zero or more times).'$1'
.Upvotes: 11