user5617839
user5617839

Reputation:

Remove n amount of characters from a given index of a string in javascript

I am trying to remove n amount of characters from a given index. Here are the instructions:

"Write a function called removeFromString, which accepts a string, a starting index (number) and a number of characters to remove.

The function should return a new string with the characters removed."

Here is what I have so far:

function removeFromString(str, index, number) {
  var sliced = str.slice(index, -number);
  return sliced;
}

console.log(
  removeFromString('This is a string', 5, 5)
  );

It is sort of working, BUT for some reason in addition to removing characters from the given index, it also removes characters from the end of the string. What am I doing wrong?

Upvotes: 2

Views: 2056

Answers (5)

Bogdan Krstic
Bogdan Krstic

Reputation: 11

This should work:

function removeFromString(str, start, removeCount) {
  let newStr = '';

  for (let i = 0; i < str.length; i++) {

    if (i < start || i >= start + removeCount) {

      newStr += str[i];
    }
  }
  return newStr;
}

let test = removeFromString('this is a test', 4, 6);
console.log(test);

Upvotes: 0

Cat
Cat

Reputation: 4226

If you convert the String to an Array, you can use the powerful array.splice method. Here's an intentionally verbose example:

let str = "Harry Potter-Evans-Verres and the Methods of Rationality"
removeFromString(str, 12, 13);

function removeFromString(string, startAt, howMany){

  const array = Array.from(string)
  removedArray = array.splice(12, 13);
  let remainingString = array.join("");

  let removedString = removedArray.join("");
  console.log({remainingString});
  console.log({removedString});

  return remainingString;
}

Upvotes: 0

fubar
fubar

Reputation: 383

For the Nerds

function removeFromString(str,index,number){
  return str.split('').fill('',index,index+number).join('')
}
console.log(removeFromString('This is a string',5,5))

Upvotes: 1

Jagadeesh
Jagadeesh

Reputation: 50

function removeFromString(str, index, number) {
  var outputStringArray = str.split('');
  outputStringArray.splice(index, number);
  return outputStringArray.join('');
}

console.log(
  removeFromString('This is a string', 5, 5)
  );

Upvotes: 3

Yousername
Yousername

Reputation: 1012

Slice returns the extracted string... so, put two extracted strings together.

function removeFromString(str, index, number) {
  var sliced = str.slice(0, index) + str.slice(index + number);
  return sliced;
}

console.log(
  removeFromString('This is a string', 5, 5)
);

Upvotes: 2

Related Questions