Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove string from string by range using JS [duplicate]

I don`t know the easy way how to remove text from text by range in JS.

I read a lot of questions there, but no one help me.

I dont want to user replace, etc. Just remove.

Example:

jakxxxjakxxx => remove 4 - 6 returns jakjakxxx

jakxxxjakxxx => remove 0 - 2 returns xxxjakxxx

Is there any function is standard js library?

like image 297
hiacliok Avatar asked Dec 28 '25 23:12

hiacliok


2 Answers

I'd offer a different solution than Nina's, here it is with 2 substring calls:

function remove(string, from, to) {
  return string.substring(0, from) + string.substring(to);
}

No need to transform into an array iterating the characters.

Note: Remember that we start counting from 0.

like image 136
Madara's Ghost Avatar answered Dec 30 '25 22:12

Madara's Ghost


You could filter the letters.

function remove(string, from, to) {
    return [...string].filter((_, i) => i < from || i > to).join('');
}

console.log(remove('jakxxxjakxxx', 4, 6)); // jakjakxxx 
console.log(remove('jakxxxjakxxx', 0, 2)); // xxxjakxxx
                    012345678901

Or slice the string.

function remove(string, from, to) {
    return string.slice(0, from) + string.slice(to);
}

console.log(remove('jakxxxjakxxx', 4, 6)); // jakjakxxx 
console.log(remove('jakxxxjakxxx', 0, 2)); // xxxjakxxx
like image 37
Nina Scholz Avatar answered Dec 31 '25 00:12

Nina Scholz