-1

Add a removeLetter function that takes a string and a letter. The result of the function should be string, which does not have the specified character in letter. How to do peple?

function deleteLetter(string, letter) {
  let final = '';
  for (let i = 0; i<string.length; i++) {
   if (string[i] === letter) {
     final.concat(string[i])
   }
   return final;
  }
}
  • What about https://stackoverflow.com/questions/9932957/how-can-i-remove-a-character-from-a-string-using-javascript? – Nico Haase Aug 24 '20 at 07:29
  • [String.prototype.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) – Lain Aug 24 '20 at 07:29

5 Answers5

2

You should return the result at the end of the function, not in the for loop

function deleteLetter(string, letter) {
  let final = ""
  for (let i = 0; i < string.length; i++) {
    if (string[i] !== letter) {
      final += string[i]
    }
  }
  return final
}

console.log(deleteLetter("asdasd", "a"))
hgb123
  • 13,869
  • 3
  • 20
  • 38
1

With ES2021 you'll be able to use String.replaceAll (already available on firefox stable (79) and chrome beta(85)/canary(86))

console.log("test".replaceAll("t", ""))
jonatjano
  • 3,576
  • 1
  • 15
  • 20
  • you can see the compatibility here → https://kangax.github.io/compat-table/es2016plus/#test-String.prototype.replaceAll – jonatjano Aug 24 '20 at 07:33
  • I'm using Chrome 84.0.4147.135 and got *"Uncaught TypeError: \"test\".replaceAll is not a function"*. – Cid Aug 24 '20 at 07:37
  • 1
    @Cid I missread the compatibility table, chrome only has it in beta (85) and canary (86) on chrome 84 you need to set a flag, modifying the answer – jonatjano Aug 24 '20 at 07:44
0

You can just use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

let str = 'test'
let replaced = str.replace('e', '')
console.log(replaced) // tst

But remember that only first occurrence will be replaced when u use string as first parameter. Use regex solution when you want to remove all of the letters

Magiczne
  • 1,586
  • 2
  • 15
  • 23
0
const removeLetter = (str, letter) =>
  str.split('').filter(n => !n.includes(letter)).join('');

console.log(removeLetter('asd', 'a'));

or

const removeLetter = (str, letter) => str.replace(/[^letter]/, '');

console.log(removeLetter('asd', 'a'));
Tigran Abrahamyan
  • 756
  • 1
  • 4
  • 7
0

using splice & indexOf

function delLetter(word,letter){
  let wordArr = word.split('');
    let idx = wordArr.indexOf(letter);
    wordArr.splice(idx,1); // deleted here
  return wordArr.join('');
}

console.log(delLetter('twinkle','w'))
KcH
  • 3,302
  • 3
  • 21
  • 46