Home > Mobile >  How to create a function to remove a string from a string with a starting index and number of charac
How to create a function to remove a string from a string with a starting index and number of charac

Time:01-01

I need a function to remove a string from a string and return the original string with the substring removed using an index to start the removal at and a count of how many characters to remove.

function removeFromString(str, index, count) {
    let char = (count   index);
    (str.slice(index, char))
    console.log (str);
}
``

Im expecting to get the original string returned with the characters indicated removed. I wrote this wrong previously.

CodePudding user response:

You need to pass the end index (exclusive) to slice, not the count.

function removeFromString(str, index, count) {
    return str.slice(index, index   count);
}
console.log(removeFromString("abcde", 2, 1));
console.log(removeFromString("abcde", 1, 10));

CodePudding user response:

The String length property gives you to the total number of chars in a string. For example:

"String".length = 6

the slice function cuts up a string but is indexed 0. so for the string "String" 0 - 5.

if your start index is greater that or equal to the string length you'll get an empty string.

you can review the docs here for the slice function

  • Related