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
try
S = S.substring(0, bindex)+S.substring(eindex);
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')
);
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"
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)
);