how can i remove chars between indexes in a javascript string

前端 未结 10 2394
无人及你
无人及你 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:08

    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('');
    
    0 讨论(0)
  • 2020-12-17 10:13

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

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

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

    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"

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

    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)

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

    With String.slice:

    S = S.slice(0, bindex) + S.slice(eindex);
    
    0 讨论(0)
提交回复
热议问题