How to replace/delete all BUT the first character in a string

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”.


solution

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'
  • 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, '$1'.