ad smith
ad smith

Reputation: 39

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

Upvotes: 3

Views: 3358

Answers (1)

Josh Crozier
Josh Crozier

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'
  • 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'.

Upvotes: 11

Related Questions