how can i remove chars between indexes in a javascript string

前端 未结 10 2395
无人及你
无人及你 2020-12-17 09:39

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

相关标签:
10条回答
  • 2020-12-17 10:23

    try

    S = S.substring(0, bindex)+S.substring(eindex);
    
    0 讨论(0)
  • 2020-12-17 10:25

    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')
    );

    0 讨论(0)
  • 2020-12-17 10:27

    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"
    
    0 讨论(0)
  • 2020-12-17 10:27

    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)
    );

    0 讨论(0)
提交回复
热议问题