How to replace/delete all BUT the first character in a string
Sample: If my string is “apple” and i would only want “a”.
You don’t need regular expressions to remove all but the first character(s) in a string.
'apple'.slice(0, 1); // 'a'
You can also just access the first character using the
'apple'.charAt(0); // 'a'
If you want to use the
.replace() method, then you could use the following:
'apple'.replace(/(^.).*/, '$1'); // 'a'
- In regular expressions, the
.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).
- Then we are essentially replacing everything with the first capture group,