Home > OS >  How can I remove characters from a string given in an array
How can I remove characters from a string given in an array

Time:05-24

for self development purposes I want to create a function with two parameters - string and an array. It should return a string without the letters given in the array.

function filterLetters(str, lettersToRemove) {

}

const str = filterLetters('Achievement unlocked', ['a', 'e']);

Could someone give me any pointers on how to achieve this?

CodePudding user response:

You can use regex with replaceAll to remove all char from the string.

If you want to consider upper case also then use 'gi' else no need for regex also. str.replaceAll(char, '')

const removeChar = (str, c) => str.replaceAll(new RegExp(`[${c}]`, "gi"), "");

const run = () => {
  const str = "Achievement unlocked";
  const chars = ["a", "e"];

  let result = str;
  chars.forEach((char) => {
    result = removeChar(result, char);
  });
  return result;
};

console.log(run());

CodePudding user response:

For each letter to be replaced, replace it. When done, return the updated string:

function filterLetters(str, lettersToRemove) {
    lettersToRemove.forEach(function(letter){
        str = str.replaceAll(letter, '');
    })
    return str
}

Also see How to replace all occurrences of a string in JavaScript.

CodePudding user response:

One easy way to do this would be to just loop over each value in the array and call the replace string method on str with each indices character. The code below does this.

function filterLetters(str, lettersToRemove){
   for (const letter of lettersToRemove){
      str = str.replaceAll(letter,"");
   }
   return str;
}

CodePudding user response:

You should just transform the string into array by using split function and loop over that array and check if each character exist in the second argument of your function. To make this function not case sensitive I use toLowerCase to convert character to

function filterLetters(str, lettersToRemove) {
  return str.split('').reduce((acc, current)=> {
    if(lettersToRemove.indexOf(current.toLowerCase()) == -1){
      acc.push(current);
    }
    return acc;
  }, []).join('');
}

const str = filterLetters('Achievement unlocked', ['a', 'e']);

console.log(str);

CodePudding user response:

Create a regular expression by joining the array elements with a | (so a|e), and then use replaceAll to match those letters and replace them with an empty string.

If you want both upper- and lower-case letters removed add the "case-insenstive" flag to the regex. 'gi' rather than 'g'.

function filterLetters(str, lettersToRemove) {
  const re = new RegExp(lettersToRemove.join('|'), 'g');
  return str.replaceAll(re, '');
}

const str = filterLetters('Achievement unlocked', ['a', 'e']);

console.log(str);

  • Related