简体   繁体   中英

Remove only the first unnecessary letter from a string

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?

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', '');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM