Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
Making a function using .replace() to remove multiple characters in a variable string?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!