Home > Enterprise >  Making a function using .replace() to remove multiple characters in a variable string?
Making a function using .replace() to remove multiple characters in a variable string?

Time:06-26

The function accepts 3 inputs: (string (str), starting point in string (index), and how many characters to remove after that (count)).

function removeFromString(str, index, count) {
  let newStr = '';
  for (let i = index; i <= (index   count); i  ) {
    newStr = str.replace(str[i], '');
  }
  return newStr;
}

It's returning outputs that may remove one character at most, but nothing more than that, which is not what I am trying to achieve.

What I want is a function that when called, will return a function without the characters specified from the index and count parameters.

CodePudding user response:

With

newStr = str.replace(str[i], '')

you're always taking str as the base string to replace - which is the original input. You're never using the newStr except after the final iteration; all replacements made before then are lost.

Another problem is that str.replace(str[i], '') will replace the same character if it exists earlier in the string, rather than at the index you want.

Slice the string's indicies instead.

const removeFromString = (str, index, count) => (
  str.slice(0, index   1)   str.slice(index   count   1)
);
console.log(removeFromString('123456', 2, 2));

CodePudding user response:

Is just a matter of use substring method from JS.

Substring method definition from Mozilla Developer Network

function removeFromString(str, index, count) {
   return str.substring(0, index)   str.substring(index count);
}
console.log(removeFromString('fofonka', 2, 2));
  • Related