Home > Software design >  Remove only the first unnecessary letter from a string
Remove only the first unnecessary letter from a string

Time:05-24

for learning purposes I want to remove only the FIRST letter 'a' from a string using a function. My function however removes ALL letters 'a' from the given string.

function removeFirstLetterA(str) {
  let letterA = 'a';
  for (let i = 0; i < str.length; i  ) {
    if (str[i] === letterA) {
      str = str.replace(letterA, '');
    } 
}

return str;
}

Can anyone see my mistake and give any tips?

CodePudding user response:

The mistake is that you don't stop when you come across and delete the first letter. Inside the if-block, you can break the loop, so that it won't continue after deleting the first one.

...
if (str[i] === letterA) {
  str = str.replace(letterA, '');
  break;
} 
...

Btw, you don't need a loop to delete the first match. Replace already does that. This would be enough:

function removeFirstLetterA(str) {
    return str.replace('a', '');
}
  • Related