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
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('');
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"
S.split(S.substring(bindex, eindex)).join(" ");
Take the text before bindex and concatenate with text after eindex, like:
var S="hi how are you";
var bindex = 2; var eindex = 6;
S = S.substr(0, bindex) + S.substr(eindex);
S is now "hi are you"
You can:
rebuild the string
var new_s = S.slice(1, bindex) + S.slice(bindex, eindex).replace(/\s/g, '') + S.slice(eindex)
With String.slice:
S = S.slice(0, bindex) + S.slice(eindex);