0

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.

2 Answers 2

1

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));

Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't that second example return 1236?
1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.