32

i have the following:

var S="hi how are you";
var bindex = 2;
var eindex = 6;

how can i remove all the chars from S that reside between bindex and eindex?
therefore S will be "hi are you"

11 Answers 11

60

Take the text before bindex and concatenate with text after eindex, like:

var S = "hi how are you";
console.log(S)
var bindex = 2;
var eindex = 6;
S = S.substr(0, bindex) + S.substr(eindex);
console.log(S)

S is now "hi are you"

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

5 Comments

This seems like the safest approach. Should be the accepted answer
I like this one, it avoids friendly fire.
I agree too that this answer should be the accepted answer.
The new alternative is just substring instead.
20

First find the substring of the string to replace, then replace the first occurrence of that string with the empty string.

S = S.replace(S.substring(bindex, eindex), "");

Another way is to convert the string to an array, splice out the unwanted part and convert to string again.

var result = S.split('');
result.splice(bindex, eindex - bindex);
S = result.join('');

3 Comments

The first method could replace more things than you expect.
Going further, the second method will do weird stuff if unicode is present in the string. (as you're splitting using '')
.replace() only replaces the first occurrence of the given string. If anything, this method would remove something unnecessary
13

try

S = S.substring(0, bindex)+S.substring(eindex);

Comments

9

With String.slice:

S = S.slice(0, bindex) + S.slice(eindex);

1 Comment

This seems like it would be more efficient if you already knew the indexes anyway.
3

A solution that doesn't require creating any intermediate arrays or strings is to use .replace to capture the first characters in a group, match the characters you want to remove, and replace with the first captured group:

// keep first 3 characters, remove next 4 characters
const s = "hi how are you";
console.log(
  s.replace(/(.{3}).{4}/, '$1')
);

Comments

2

S.split(S.substring(bindex, eindex)).join(" ");

Comments

1

You can:

  1. get the substring from bindex and eindex
  2. remove spaces from that string
  3. rebuild the string

    var new_s = S.slice(1, bindex) + S.slice(bindex, eindex).replace(/\s/g, '') + S.slice(eindex)

1 Comment

Sorry. I misread your question, reading 'remove all spaces' instead of 'remove all the chars'
1

DON'T USE SLICE; TRY SPLICE

While slice is good and all, it was designed like substring, it was designed to get stuff, not remove stuff.

Caveat: splice was written for Arrays.

Good news: strings are easily turned into Arrays.

String.prototype.splice = function(start, deleteCount) {
  const newStringArray = this.split('')
  newStringArray.splice(start, deleteCount)
  return newStringArray.join('')
}

'Hello World'.splice(2, 5)
// Output -> "Heorld"

1 Comment

This doesn't really explain why you shouldn't use slice - it was designed to get parts of a string, and that's what it's doing in the above examples (even if the end result is to put the strings back together). The split and join operations will make this function WAY slower.
1

The following function returns the complementary result of slice function:

 String.prototype.remainderOfSlice = function(begin, end) {

    begin = begin || 0
    end = (end === undefined) ? this.length : end 

    if (this.slice(begin, end) === '') return this + ''
    return this.slice(0, begin) + this.slice(end) 
 }

examples:

 "hi how are you".slice(2, 6) // " how"
 "hi how are you".remainderOfSlice(2, 6) // "hi are you"

 "hi how are you".slice(-2, 6) // ""
 "hi how are you".remainderOfSlice(-2, 6) // "hi how are you"

Comments

0

Want to delete multiple ranges in a string at once? It can be tricky because indexes will change as you cut out pieces of a string, but here's something quick that might work depending on your requirements:

function deleteRangesInString(ranges, string, deleteChar = "▮") {
    ranges.forEach(r => {
        string = string.substring(0, r[0]) + deleteChar.repeat((r[1]-r[0])+1) + string.substring(r[1]+1);
    })
    return string.replace(new RegExp(deleteChar, 'g'), '');
}

var s = 'hi how are you, look at me now, look at me now';

console.log(
deleteRangesInString([[2,9],[14,29]], s)
);

Comments

0

Assuming you have only the beginning index bindex and length of the string you want to remove while the end index is indeterminate.

Typical use case for this is in cryptography, where you want to remove salt from a decrypted string (that was inserted at a known index before encryption) without exposing the value of the salt; you can expose the salt length rather than the salt value.

function removeSalt(str, bindex, saltlen) {
    
    let front = str.slice(0, bindex)
    return front + str.slice(front.length + saltlen)
}

var s = "how was45r7% your day?" // can be result from a decryption function
console.log (removeSalt(s, 7, 5))

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.