Is there a splice method for strings?











up vote
63
down vote

favorite
17












The Javascript splice only works with arrays. Is there similar method for strings? Or should I create my own custom function?



The substr(), and substring() methods will only return the extracted string and not modify the original string. What I want to do is remove some part from my string and apply the change to the original string. Moreover, the method replace() will not work in my case because I want to remove parts starting from an index and ending at some other index, exactly like what I can do with the splice() method. I tried converting my string to an array, but this is not a neat method.










share|improve this question
























  • str.split might be the function you're looking for: google.com/#q=javascript+string+split
    – Anderson Green
    Dec 28 '13 at 18:03








  • 1




    What's wrong with str = str.slice()?
    – elclanrs
    Dec 28 '13 at 18:04






  • 1




    Looks like an XY problem, what are you trying to do exactly? Strings are not passed by reference, unlike arrays and objects, so you don't mutate strings, you create new ones or re-assign the new one to the old one.
    – elclanrs
    Dec 28 '13 at 18:06








  • 1




    possible duplicate of Set String via String.prototype function without return
    – raina77ow
    Dec 28 '13 at 18:06






  • 6




    return string.slice(0, startToSplice) + string.slice(endToSplice);, no?
    – raina77ow
    Dec 28 '13 at 18:12















up vote
63
down vote

favorite
17












The Javascript splice only works with arrays. Is there similar method for strings? Or should I create my own custom function?



The substr(), and substring() methods will only return the extracted string and not modify the original string. What I want to do is remove some part from my string and apply the change to the original string. Moreover, the method replace() will not work in my case because I want to remove parts starting from an index and ending at some other index, exactly like what I can do with the splice() method. I tried converting my string to an array, but this is not a neat method.










share|improve this question
























  • str.split might be the function you're looking for: google.com/#q=javascript+string+split
    – Anderson Green
    Dec 28 '13 at 18:03








  • 1




    What's wrong with str = str.slice()?
    – elclanrs
    Dec 28 '13 at 18:04






  • 1




    Looks like an XY problem, what are you trying to do exactly? Strings are not passed by reference, unlike arrays and objects, so you don't mutate strings, you create new ones or re-assign the new one to the old one.
    – elclanrs
    Dec 28 '13 at 18:06








  • 1




    possible duplicate of Set String via String.prototype function without return
    – raina77ow
    Dec 28 '13 at 18:06






  • 6




    return string.slice(0, startToSplice) + string.slice(endToSplice);, no?
    – raina77ow
    Dec 28 '13 at 18:12













up vote
63
down vote

favorite
17









up vote
63
down vote

favorite
17






17





The Javascript splice only works with arrays. Is there similar method for strings? Or should I create my own custom function?



The substr(), and substring() methods will only return the extracted string and not modify the original string. What I want to do is remove some part from my string and apply the change to the original string. Moreover, the method replace() will not work in my case because I want to remove parts starting from an index and ending at some other index, exactly like what I can do with the splice() method. I tried converting my string to an array, but this is not a neat method.










share|improve this question















The Javascript splice only works with arrays. Is there similar method for strings? Or should I create my own custom function?



The substr(), and substring() methods will only return the extracted string and not modify the original string. What I want to do is remove some part from my string and apply the change to the original string. Moreover, the method replace() will not work in my case because I want to remove parts starting from an index and ending at some other index, exactly like what I can do with the splice() method. I tried converting my string to an array, but this is not a neat method.







javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 18 '14 at 11:22









Louis

91.8k22178226




91.8k22178226










asked Dec 28 '13 at 18:00









ProllyGeek

12.5k53466




12.5k53466












  • str.split might be the function you're looking for: google.com/#q=javascript+string+split
    – Anderson Green
    Dec 28 '13 at 18:03








  • 1




    What's wrong with str = str.slice()?
    – elclanrs
    Dec 28 '13 at 18:04






  • 1




    Looks like an XY problem, what are you trying to do exactly? Strings are not passed by reference, unlike arrays and objects, so you don't mutate strings, you create new ones or re-assign the new one to the old one.
    – elclanrs
    Dec 28 '13 at 18:06








  • 1




    possible duplicate of Set String via String.prototype function without return
    – raina77ow
    Dec 28 '13 at 18:06






  • 6




    return string.slice(0, startToSplice) + string.slice(endToSplice);, no?
    – raina77ow
    Dec 28 '13 at 18:12


















  • str.split might be the function you're looking for: google.com/#q=javascript+string+split
    – Anderson Green
    Dec 28 '13 at 18:03








  • 1




    What's wrong with str = str.slice()?
    – elclanrs
    Dec 28 '13 at 18:04






  • 1




    Looks like an XY problem, what are you trying to do exactly? Strings are not passed by reference, unlike arrays and objects, so you don't mutate strings, you create new ones or re-assign the new one to the old one.
    – elclanrs
    Dec 28 '13 at 18:06








  • 1




    possible duplicate of Set String via String.prototype function without return
    – raina77ow
    Dec 28 '13 at 18:06






  • 6




    return string.slice(0, startToSplice) + string.slice(endToSplice);, no?
    – raina77ow
    Dec 28 '13 at 18:12
















str.split might be the function you're looking for: google.com/#q=javascript+string+split
– Anderson Green
Dec 28 '13 at 18:03






str.split might be the function you're looking for: google.com/#q=javascript+string+split
– Anderson Green
Dec 28 '13 at 18:03






1




1




What's wrong with str = str.slice()?
– elclanrs
Dec 28 '13 at 18:04




What's wrong with str = str.slice()?
– elclanrs
Dec 28 '13 at 18:04




1




1




Looks like an XY problem, what are you trying to do exactly? Strings are not passed by reference, unlike arrays and objects, so you don't mutate strings, you create new ones or re-assign the new one to the old one.
– elclanrs
Dec 28 '13 at 18:06






Looks like an XY problem, what are you trying to do exactly? Strings are not passed by reference, unlike arrays and objects, so you don't mutate strings, you create new ones or re-assign the new one to the old one.
– elclanrs
Dec 28 '13 at 18:06






1




1




possible duplicate of Set String via String.prototype function without return
– raina77ow
Dec 28 '13 at 18:06




possible duplicate of Set String via String.prototype function without return
– raina77ow
Dec 28 '13 at 18:06




6




6




return string.slice(0, startToSplice) + string.slice(endToSplice);, no?
– raina77ow
Dec 28 '13 at 18:12




return string.slice(0, startToSplice) + string.slice(endToSplice);, no?
– raina77ow
Dec 28 '13 at 18:12












7 Answers
7






active

oldest

votes

















up vote
71
down vote



accepted










It is faster to slice the string twice, like this:



function spliceSlice(str, index, count, add) {
// We cannot pass negative indexes directly to the 2nd slicing operation.
if (index < 0) {
index = str.length + index;
if (index < 0) {
index = 0;
}
}

return str.slice(0, index) + (add || "") + str.slice(index + count);
}


than using a split followed by a join (Kumar Harsh's method), like this:



function spliceSplit(str, index, count, add) {
var ar = str.split('');
ar.splice(index, count, add);
return ar.join('');
}


Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)



Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.






share|improve this answer



















  • 1




    To me this is much better than converting the string into an array and creating separate strings for each character in the array (like the chosen answer)
    – Juan Mendes
    Jun 2 '14 at 19:20








  • 2




    You can add this globally with: String.prototype.splice = function (index, count, add) { return this.slice(0, index) + (add || "") + this.slice(index + count); } Just keep in mind it doesn't work exactly the same as the array splice method because strings are immutable (you can't modify them once created). So usage would be like: var s="ss"; s = s.splice(0,1,"t");
    – William Neely
    Nov 18 '14 at 16:52












  • @WilliamNeely: var StringUtils={'StringSplice':/*func def*/}; would be standard for string manipulation as you have said that it is immutable.
    – Mr. Polywhirl
    Nov 25 '14 at 16:37












  • spliceSlice and spliceSplit are not functionally equal due to Array.prototype.splice accepting negative indices: jsfiddle.net/sykteho6/5.
    – Martijn
    Jul 4 '16 at 13:35






  • 1




    @Mzialla Thanks, I've added code to take care of it.
    – Louis
    Jul 4 '16 at 14:13


















up vote
13
down vote













Edit



This is of course not the best way to "splice" a string, I had given this as an example of how the implementation would be, which is flawed and very evident from a split(), splice() and join(). For a far better implementation, see Louis's method.





No, there is no such thing as a String.splice, but you can try this:



newStr = str.split(''); // or newStr = [...str];
newStr.splice(2,5);
newStr = newStr.join('');


I realise there is no splice function as in Arrays, so you have to convert the string into an array. Hard luck...






share|improve this answer























  • give an example please .
    – ProllyGeek
    Dec 28 '13 at 18:08










  • Here's an example: stackoverflow.com/a/3568968/975097
    – Anderson Green
    Dec 28 '13 at 18:09










  • in my case im working on a dynamic string so i need to specify indices and not character value .
    – ProllyGeek
    Dec 28 '13 at 18:11






  • 2




    I'm sorry, but where??? You've linked to slice not splice
    – kumar_harsh
    May 20 '16 at 7:37






  • 2




    Instead of using str.split, you can use ES6 spread syntax like so: [...str]
    – robbie0630
    Apr 26 '17 at 14:01


















up vote
4
down vote













Here's a nice little Curry which lends better readability (IMHO):



The second function's signature is identical to the Array.prototype.splice method.



function mutate(s) {
return function splice() {
var a = s.split('');
Array.prototype.splice.apply(a, arguments);
return a.join('');
};
}

mutate('101')(1, 1, '1');


I know there's already an accepted answer, but hope this is useful.






share|improve this answer



















  • 1




    Np. You can even abstract this to allow, say, an optional 'method' parameter so you can pass in an Array.prototype[method] and treat strings completely like arrays. Also, with this one alone, you could abstract the actual process to another function -- and if there's no string, return a function that will take the string and reverse the curry: mutate()(1, 1, '1')('101'); You could even duckType the arguments to rid the curry of the empty invocation -- even encapsulate a method, itself. If you need this stuff, you may want to look into the Command Pattern though. Just spit-balling here.
    – Cody
    Aug 16 '16 at 20:03




















up vote
3
down vote













The method Louis's answer, as a String prototype function:



String.prototype.splice = function(index, count, add) {
if (index < 0) {
index = this.length + index;
if (index < 0) {
index = 0;
}
}
return this.slice(0, index) + (add || "") + this.slice(index + count);
}


Example:



 > "Held!".splice(3,0,"lo Worl")
< "Hello World!"





share|improve this answer






























    up vote
    2
    down vote













    I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).



    String.prototype.splice = function(startIndex,length,insertString){
    return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
    };


    You can use it like this:



    var creditCardNumber = "5500000000000004";
    var cardSuffix = creditCardNumber.splice(0,12,'****');
    console.log(cardSuffix); // output: ****0004


    See Test Results:
    https://jsfiddle.net/0quz9q9m/5/






    share|improve this answer





















    • you should at least do ` + (insertString || "") + ` instead of ` + insertString + , otherwise the third argument is not optional. This implementation also doesn't take care of startIndex < 0` unlike other suggestions. Great example of usage, though
      – YakovL
      Nov 11 at 10:37




















    up vote
    2
    down vote













    Simply use substr for string



    ex.



    var str = "Hello world!";
    var res = str.substr(1, str.length);


    Result = ello world!






    share|improve this answer




























      up vote
      0
      down vote













      There seem to be a lot of confusion which was addressed only in comments by elclanrs and raina77ow, so let me post a clarifying answer.



      Clarification



      From "string.splice" one may expect that it, like the one for arrays:




      • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

      • returns the cut out part

      • modifies the original string


      The problem is, the 3d requirement can not be fulfilled because strings are immutable (related: 1, 2), I've found the most dedicated comment here:




      In JavaScript strings are primitive value types and not objects (spec). In fact, as of ES5, they're one of the only 5 value types alongside null, undefined, number and boolean. Strings are assigned by value and not by reference and are passed as such. Thus, strings are not just immutable, they are a value. Changing the string "hello" to be "world" is like deciding that from now on the number 3 is the number 4... it makes no sense.




      So, with that in account, one may expect the "string.splice" thing to only:




      • accepts up to 2 arguments: start position, length (insertion makes no sense since the string is not changed)

      • returns the cut out part


      which is what substr does; or, alternatively,




      • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

      • returns the modified string (without the cut part and with insertion)


      which is the subject of the next section.



      Solutions



      If you care about optimizing, you should probably use the Mike's implementation:



      String.prototype.splice = function(index, count, add) {
      if (index < 0) {
      index += this.length;
      if (index < 0)
      index = 0;
      }
      return this.slice(0, index) + (add || "") + this.slice(index + count);
      }


      Treating the out-of-boundaries index may vary, though. Depending on your needs, you may want:



          if (index < 0) {
      index += this.length;
      if (index < 0)
      index = 0;
      }
      if (index >= this.length) {
      index -= this.length;
      if (index >= this.length)
      index = this.length - 1;
      }


      or even



          index = index % this.length;
      if (index < 0)
      index = this.length + index;


      If you don't care about performance, you may want to adapt Kumar's suggestion which is more straight-forward:



      String.prototype.splice = function(index, count, add) {
      var chars = this.split('');
      chars.splice(index, count, add);
      return chars.join('');
      }


      Performance



      The difference in performances increases drastically with the length of the string. jsperf shows, that for strings with the length of 10 the latter solution (splitting & joining) is twice slower than the former solution (using slice), for 100-letter strings it's x5 and for 1000-letter strings it's x50, in Ops/sec it's:



                            10 letters   100 letters   1000 letters
      slice implementation 1.25 M 2.00 M 1.91 M
      split implementation 0.63 M 0.22 M 0.04 M


      note that I've changed the 1st and 2d arguments when moving from 10 letters to 100 letters (still I'm surprised that the test for 100 letters runs faster than that for 10 letters).






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20817618%2fis-there-a-splice-method-for-strings%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        7 Answers
        7






        active

        oldest

        votes








        7 Answers
        7






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        71
        down vote



        accepted










        It is faster to slice the string twice, like this:



        function spliceSlice(str, index, count, add) {
        // We cannot pass negative indexes directly to the 2nd slicing operation.
        if (index < 0) {
        index = str.length + index;
        if (index < 0) {
        index = 0;
        }
        }

        return str.slice(0, index) + (add || "") + str.slice(index + count);
        }


        than using a split followed by a join (Kumar Harsh's method), like this:



        function spliceSplit(str, index, count, add) {
        var ar = str.split('');
        ar.splice(index, count, add);
        return ar.join('');
        }


        Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)



        Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.






        share|improve this answer



















        • 1




          To me this is much better than converting the string into an array and creating separate strings for each character in the array (like the chosen answer)
          – Juan Mendes
          Jun 2 '14 at 19:20








        • 2




          You can add this globally with: String.prototype.splice = function (index, count, add) { return this.slice(0, index) + (add || "") + this.slice(index + count); } Just keep in mind it doesn't work exactly the same as the array splice method because strings are immutable (you can't modify them once created). So usage would be like: var s="ss"; s = s.splice(0,1,"t");
          – William Neely
          Nov 18 '14 at 16:52












        • @WilliamNeely: var StringUtils={'StringSplice':/*func def*/}; would be standard for string manipulation as you have said that it is immutable.
          – Mr. Polywhirl
          Nov 25 '14 at 16:37












        • spliceSlice and spliceSplit are not functionally equal due to Array.prototype.splice accepting negative indices: jsfiddle.net/sykteho6/5.
          – Martijn
          Jul 4 '16 at 13:35






        • 1




          @Mzialla Thanks, I've added code to take care of it.
          – Louis
          Jul 4 '16 at 14:13















        up vote
        71
        down vote



        accepted










        It is faster to slice the string twice, like this:



        function spliceSlice(str, index, count, add) {
        // We cannot pass negative indexes directly to the 2nd slicing operation.
        if (index < 0) {
        index = str.length + index;
        if (index < 0) {
        index = 0;
        }
        }

        return str.slice(0, index) + (add || "") + str.slice(index + count);
        }


        than using a split followed by a join (Kumar Harsh's method), like this:



        function spliceSplit(str, index, count, add) {
        var ar = str.split('');
        ar.splice(index, count, add);
        return ar.join('');
        }


        Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)



        Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.






        share|improve this answer



















        • 1




          To me this is much better than converting the string into an array and creating separate strings for each character in the array (like the chosen answer)
          – Juan Mendes
          Jun 2 '14 at 19:20








        • 2




          You can add this globally with: String.prototype.splice = function (index, count, add) { return this.slice(0, index) + (add || "") + this.slice(index + count); } Just keep in mind it doesn't work exactly the same as the array splice method because strings are immutable (you can't modify them once created). So usage would be like: var s="ss"; s = s.splice(0,1,"t");
          – William Neely
          Nov 18 '14 at 16:52












        • @WilliamNeely: var StringUtils={'StringSplice':/*func def*/}; would be standard for string manipulation as you have said that it is immutable.
          – Mr. Polywhirl
          Nov 25 '14 at 16:37












        • spliceSlice and spliceSplit are not functionally equal due to Array.prototype.splice accepting negative indices: jsfiddle.net/sykteho6/5.
          – Martijn
          Jul 4 '16 at 13:35






        • 1




          @Mzialla Thanks, I've added code to take care of it.
          – Louis
          Jul 4 '16 at 14:13













        up vote
        71
        down vote



        accepted







        up vote
        71
        down vote



        accepted






        It is faster to slice the string twice, like this:



        function spliceSlice(str, index, count, add) {
        // We cannot pass negative indexes directly to the 2nd slicing operation.
        if (index < 0) {
        index = str.length + index;
        if (index < 0) {
        index = 0;
        }
        }

        return str.slice(0, index) + (add || "") + str.slice(index + count);
        }


        than using a split followed by a join (Kumar Harsh's method), like this:



        function spliceSplit(str, index, count, add) {
        var ar = str.split('');
        ar.splice(index, count, add);
        return ar.join('');
        }


        Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)



        Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.






        share|improve this answer














        It is faster to slice the string twice, like this:



        function spliceSlice(str, index, count, add) {
        // We cannot pass negative indexes directly to the 2nd slicing operation.
        if (index < 0) {
        index = str.length + index;
        if (index < 0) {
        index = 0;
        }
        }

        return str.slice(0, index) + (add || "") + str.slice(index + count);
        }


        than using a split followed by a join (Kumar Harsh's method), like this:



        function spliceSplit(str, index, count, add) {
        var ar = str.split('');
        ar.splice(index, count, add);
        return ar.join('');
        }


        Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)



        Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 19 at 14:56









        Lorenz Meyer

        12.3k195093




        12.3k195093










        answered Jan 25 '14 at 12:37









        Louis

        91.8k22178226




        91.8k22178226








        • 1




          To me this is much better than converting the string into an array and creating separate strings for each character in the array (like the chosen answer)
          – Juan Mendes
          Jun 2 '14 at 19:20








        • 2




          You can add this globally with: String.prototype.splice = function (index, count, add) { return this.slice(0, index) + (add || "") + this.slice(index + count); } Just keep in mind it doesn't work exactly the same as the array splice method because strings are immutable (you can't modify them once created). So usage would be like: var s="ss"; s = s.splice(0,1,"t");
          – William Neely
          Nov 18 '14 at 16:52












        • @WilliamNeely: var StringUtils={'StringSplice':/*func def*/}; would be standard for string manipulation as you have said that it is immutable.
          – Mr. Polywhirl
          Nov 25 '14 at 16:37












        • spliceSlice and spliceSplit are not functionally equal due to Array.prototype.splice accepting negative indices: jsfiddle.net/sykteho6/5.
          – Martijn
          Jul 4 '16 at 13:35






        • 1




          @Mzialla Thanks, I've added code to take care of it.
          – Louis
          Jul 4 '16 at 14:13














        • 1




          To me this is much better than converting the string into an array and creating separate strings for each character in the array (like the chosen answer)
          – Juan Mendes
          Jun 2 '14 at 19:20








        • 2




          You can add this globally with: String.prototype.splice = function (index, count, add) { return this.slice(0, index) + (add || "") + this.slice(index + count); } Just keep in mind it doesn't work exactly the same as the array splice method because strings are immutable (you can't modify them once created). So usage would be like: var s="ss"; s = s.splice(0,1,"t");
          – William Neely
          Nov 18 '14 at 16:52












        • @WilliamNeely: var StringUtils={'StringSplice':/*func def*/}; would be standard for string manipulation as you have said that it is immutable.
          – Mr. Polywhirl
          Nov 25 '14 at 16:37












        • spliceSlice and spliceSplit are not functionally equal due to Array.prototype.splice accepting negative indices: jsfiddle.net/sykteho6/5.
          – Martijn
          Jul 4 '16 at 13:35






        • 1




          @Mzialla Thanks, I've added code to take care of it.
          – Louis
          Jul 4 '16 at 14:13








        1




        1




        To me this is much better than converting the string into an array and creating separate strings for each character in the array (like the chosen answer)
        – Juan Mendes
        Jun 2 '14 at 19:20






        To me this is much better than converting the string into an array and creating separate strings for each character in the array (like the chosen answer)
        – Juan Mendes
        Jun 2 '14 at 19:20






        2




        2




        You can add this globally with: String.prototype.splice = function (index, count, add) { return this.slice(0, index) + (add || "") + this.slice(index + count); } Just keep in mind it doesn't work exactly the same as the array splice method because strings are immutable (you can't modify them once created). So usage would be like: var s="ss"; s = s.splice(0,1,"t");
        – William Neely
        Nov 18 '14 at 16:52






        You can add this globally with: String.prototype.splice = function (index, count, add) { return this.slice(0, index) + (add || "") + this.slice(index + count); } Just keep in mind it doesn't work exactly the same as the array splice method because strings are immutable (you can't modify them once created). So usage would be like: var s="ss"; s = s.splice(0,1,"t");
        – William Neely
        Nov 18 '14 at 16:52














        @WilliamNeely: var StringUtils={'StringSplice':/*func def*/}; would be standard for string manipulation as you have said that it is immutable.
        – Mr. Polywhirl
        Nov 25 '14 at 16:37






        @WilliamNeely: var StringUtils={'StringSplice':/*func def*/}; would be standard for string manipulation as you have said that it is immutable.
        – Mr. Polywhirl
        Nov 25 '14 at 16:37














        spliceSlice and spliceSplit are not functionally equal due to Array.prototype.splice accepting negative indices: jsfiddle.net/sykteho6/5.
        – Martijn
        Jul 4 '16 at 13:35




        spliceSlice and spliceSplit are not functionally equal due to Array.prototype.splice accepting negative indices: jsfiddle.net/sykteho6/5.
        – Martijn
        Jul 4 '16 at 13:35




        1




        1




        @Mzialla Thanks, I've added code to take care of it.
        – Louis
        Jul 4 '16 at 14:13




        @Mzialla Thanks, I've added code to take care of it.
        – Louis
        Jul 4 '16 at 14:13












        up vote
        13
        down vote













        Edit



        This is of course not the best way to "splice" a string, I had given this as an example of how the implementation would be, which is flawed and very evident from a split(), splice() and join(). For a far better implementation, see Louis's method.





        No, there is no such thing as a String.splice, but you can try this:



        newStr = str.split(''); // or newStr = [...str];
        newStr.splice(2,5);
        newStr = newStr.join('');


        I realise there is no splice function as in Arrays, so you have to convert the string into an array. Hard luck...






        share|improve this answer























        • give an example please .
          – ProllyGeek
          Dec 28 '13 at 18:08










        • Here's an example: stackoverflow.com/a/3568968/975097
          – Anderson Green
          Dec 28 '13 at 18:09










        • in my case im working on a dynamic string so i need to specify indices and not character value .
          – ProllyGeek
          Dec 28 '13 at 18:11






        • 2




          I'm sorry, but where??? You've linked to slice not splice
          – kumar_harsh
          May 20 '16 at 7:37






        • 2




          Instead of using str.split, you can use ES6 spread syntax like so: [...str]
          – robbie0630
          Apr 26 '17 at 14:01















        up vote
        13
        down vote













        Edit



        This is of course not the best way to "splice" a string, I had given this as an example of how the implementation would be, which is flawed and very evident from a split(), splice() and join(). For a far better implementation, see Louis's method.





        No, there is no such thing as a String.splice, but you can try this:



        newStr = str.split(''); // or newStr = [...str];
        newStr.splice(2,5);
        newStr = newStr.join('');


        I realise there is no splice function as in Arrays, so you have to convert the string into an array. Hard luck...






        share|improve this answer























        • give an example please .
          – ProllyGeek
          Dec 28 '13 at 18:08










        • Here's an example: stackoverflow.com/a/3568968/975097
          – Anderson Green
          Dec 28 '13 at 18:09










        • in my case im working on a dynamic string so i need to specify indices and not character value .
          – ProllyGeek
          Dec 28 '13 at 18:11






        • 2




          I'm sorry, but where??? You've linked to slice not splice
          – kumar_harsh
          May 20 '16 at 7:37






        • 2




          Instead of using str.split, you can use ES6 spread syntax like so: [...str]
          – robbie0630
          Apr 26 '17 at 14:01













        up vote
        13
        down vote










        up vote
        13
        down vote









        Edit



        This is of course not the best way to "splice" a string, I had given this as an example of how the implementation would be, which is flawed and very evident from a split(), splice() and join(). For a far better implementation, see Louis's method.





        No, there is no such thing as a String.splice, but you can try this:



        newStr = str.split(''); // or newStr = [...str];
        newStr.splice(2,5);
        newStr = newStr.join('');


        I realise there is no splice function as in Arrays, so you have to convert the string into an array. Hard luck...






        share|improve this answer














        Edit



        This is of course not the best way to "splice" a string, I had given this as an example of how the implementation would be, which is flawed and very evident from a split(), splice() and join(). For a far better implementation, see Louis's method.





        No, there is no such thing as a String.splice, but you can try this:



        newStr = str.split(''); // or newStr = [...str];
        newStr.splice(2,5);
        newStr = newStr.join('');


        I realise there is no splice function as in Arrays, so you have to convert the string into an array. Hard luck...







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 23 '17 at 12:34









        Community

        11




        11










        answered Dec 28 '13 at 18:07









        kumar_harsh

        12.8k65584




        12.8k65584












        • give an example please .
          – ProllyGeek
          Dec 28 '13 at 18:08










        • Here's an example: stackoverflow.com/a/3568968/975097
          – Anderson Green
          Dec 28 '13 at 18:09










        • in my case im working on a dynamic string so i need to specify indices and not character value .
          – ProllyGeek
          Dec 28 '13 at 18:11






        • 2




          I'm sorry, but where??? You've linked to slice not splice
          – kumar_harsh
          May 20 '16 at 7:37






        • 2




          Instead of using str.split, you can use ES6 spread syntax like so: [...str]
          – robbie0630
          Apr 26 '17 at 14:01


















        • give an example please .
          – ProllyGeek
          Dec 28 '13 at 18:08










        • Here's an example: stackoverflow.com/a/3568968/975097
          – Anderson Green
          Dec 28 '13 at 18:09










        • in my case im working on a dynamic string so i need to specify indices and not character value .
          – ProllyGeek
          Dec 28 '13 at 18:11






        • 2




          I'm sorry, but where??? You've linked to slice not splice
          – kumar_harsh
          May 20 '16 at 7:37






        • 2




          Instead of using str.split, you can use ES6 spread syntax like so: [...str]
          – robbie0630
          Apr 26 '17 at 14:01
















        give an example please .
        – ProllyGeek
        Dec 28 '13 at 18:08




        give an example please .
        – ProllyGeek
        Dec 28 '13 at 18:08












        Here's an example: stackoverflow.com/a/3568968/975097
        – Anderson Green
        Dec 28 '13 at 18:09




        Here's an example: stackoverflow.com/a/3568968/975097
        – Anderson Green
        Dec 28 '13 at 18:09












        in my case im working on a dynamic string so i need to specify indices and not character value .
        – ProllyGeek
        Dec 28 '13 at 18:11




        in my case im working on a dynamic string so i need to specify indices and not character value .
        – ProllyGeek
        Dec 28 '13 at 18:11




        2




        2




        I'm sorry, but where??? You've linked to slice not splice
        – kumar_harsh
        May 20 '16 at 7:37




        I'm sorry, but where??? You've linked to slice not splice
        – kumar_harsh
        May 20 '16 at 7:37




        2




        2




        Instead of using str.split, you can use ES6 spread syntax like so: [...str]
        – robbie0630
        Apr 26 '17 at 14:01




        Instead of using str.split, you can use ES6 spread syntax like so: [...str]
        – robbie0630
        Apr 26 '17 at 14:01










        up vote
        4
        down vote













        Here's a nice little Curry which lends better readability (IMHO):



        The second function's signature is identical to the Array.prototype.splice method.



        function mutate(s) {
        return function splice() {
        var a = s.split('');
        Array.prototype.splice.apply(a, arguments);
        return a.join('');
        };
        }

        mutate('101')(1, 1, '1');


        I know there's already an accepted answer, but hope this is useful.






        share|improve this answer



















        • 1




          Np. You can even abstract this to allow, say, an optional 'method' parameter so you can pass in an Array.prototype[method] and treat strings completely like arrays. Also, with this one alone, you could abstract the actual process to another function -- and if there's no string, return a function that will take the string and reverse the curry: mutate()(1, 1, '1')('101'); You could even duckType the arguments to rid the curry of the empty invocation -- even encapsulate a method, itself. If you need this stuff, you may want to look into the Command Pattern though. Just spit-balling here.
          – Cody
          Aug 16 '16 at 20:03

















        up vote
        4
        down vote













        Here's a nice little Curry which lends better readability (IMHO):



        The second function's signature is identical to the Array.prototype.splice method.



        function mutate(s) {
        return function splice() {
        var a = s.split('');
        Array.prototype.splice.apply(a, arguments);
        return a.join('');
        };
        }

        mutate('101')(1, 1, '1');


        I know there's already an accepted answer, but hope this is useful.






        share|improve this answer



















        • 1




          Np. You can even abstract this to allow, say, an optional 'method' parameter so you can pass in an Array.prototype[method] and treat strings completely like arrays. Also, with this one alone, you could abstract the actual process to another function -- and if there's no string, return a function that will take the string and reverse the curry: mutate()(1, 1, '1')('101'); You could even duckType the arguments to rid the curry of the empty invocation -- even encapsulate a method, itself. If you need this stuff, you may want to look into the Command Pattern though. Just spit-balling here.
          – Cody
          Aug 16 '16 at 20:03















        up vote
        4
        down vote










        up vote
        4
        down vote









        Here's a nice little Curry which lends better readability (IMHO):



        The second function's signature is identical to the Array.prototype.splice method.



        function mutate(s) {
        return function splice() {
        var a = s.split('');
        Array.prototype.splice.apply(a, arguments);
        return a.join('');
        };
        }

        mutate('101')(1, 1, '1');


        I know there's already an accepted answer, but hope this is useful.






        share|improve this answer














        Here's a nice little Curry which lends better readability (IMHO):



        The second function's signature is identical to the Array.prototype.splice method.



        function mutate(s) {
        return function splice() {
        var a = s.split('');
        Array.prototype.splice.apply(a, arguments);
        return a.join('');
        };
        }

        mutate('101')(1, 1, '1');


        I know there's already an accepted answer, but hope this is useful.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 17 '15 at 17:26

























        answered Dec 17 '15 at 0:24









        Cody

        6,91834233




        6,91834233








        • 1




          Np. You can even abstract this to allow, say, an optional 'method' parameter so you can pass in an Array.prototype[method] and treat strings completely like arrays. Also, with this one alone, you could abstract the actual process to another function -- and if there's no string, return a function that will take the string and reverse the curry: mutate()(1, 1, '1')('101'); You could even duckType the arguments to rid the curry of the empty invocation -- even encapsulate a method, itself. If you need this stuff, you may want to look into the Command Pattern though. Just spit-balling here.
          – Cody
          Aug 16 '16 at 20:03
















        • 1




          Np. You can even abstract this to allow, say, an optional 'method' parameter so you can pass in an Array.prototype[method] and treat strings completely like arrays. Also, with this one alone, you could abstract the actual process to another function -- and if there's no string, return a function that will take the string and reverse the curry: mutate()(1, 1, '1')('101'); You could even duckType the arguments to rid the curry of the empty invocation -- even encapsulate a method, itself. If you need this stuff, you may want to look into the Command Pattern though. Just spit-balling here.
          – Cody
          Aug 16 '16 at 20:03










        1




        1




        Np. You can even abstract this to allow, say, an optional 'method' parameter so you can pass in an Array.prototype[method] and treat strings completely like arrays. Also, with this one alone, you could abstract the actual process to another function -- and if there's no string, return a function that will take the string and reverse the curry: mutate()(1, 1, '1')('101'); You could even duckType the arguments to rid the curry of the empty invocation -- even encapsulate a method, itself. If you need this stuff, you may want to look into the Command Pattern though. Just spit-balling here.
        – Cody
        Aug 16 '16 at 20:03






        Np. You can even abstract this to allow, say, an optional 'method' parameter so you can pass in an Array.prototype[method] and treat strings completely like arrays. Also, with this one alone, you could abstract the actual process to another function -- and if there's no string, return a function that will take the string and reverse the curry: mutate()(1, 1, '1')('101'); You could even duckType the arguments to rid the curry of the empty invocation -- even encapsulate a method, itself. If you need this stuff, you may want to look into the Command Pattern though. Just spit-balling here.
        – Cody
        Aug 16 '16 at 20:03












        up vote
        3
        down vote













        The method Louis's answer, as a String prototype function:



        String.prototype.splice = function(index, count, add) {
        if (index < 0) {
        index = this.length + index;
        if (index < 0) {
        index = 0;
        }
        }
        return this.slice(0, index) + (add || "") + this.slice(index + count);
        }


        Example:



         > "Held!".splice(3,0,"lo Worl")
        < "Hello World!"





        share|improve this answer



























          up vote
          3
          down vote













          The method Louis's answer, as a String prototype function:



          String.prototype.splice = function(index, count, add) {
          if (index < 0) {
          index = this.length + index;
          if (index < 0) {
          index = 0;
          }
          }
          return this.slice(0, index) + (add || "") + this.slice(index + count);
          }


          Example:



           > "Held!".splice(3,0,"lo Worl")
          < "Hello World!"





          share|improve this answer

























            up vote
            3
            down vote










            up vote
            3
            down vote









            The method Louis's answer, as a String prototype function:



            String.prototype.splice = function(index, count, add) {
            if (index < 0) {
            index = this.length + index;
            if (index < 0) {
            index = 0;
            }
            }
            return this.slice(0, index) + (add || "") + this.slice(index + count);
            }


            Example:



             > "Held!".splice(3,0,"lo Worl")
            < "Hello World!"





            share|improve this answer














            The method Louis's answer, as a String prototype function:



            String.prototype.splice = function(index, count, add) {
            if (index < 0) {
            index = this.length + index;
            if (index < 0) {
            index = 0;
            }
            }
            return this.slice(0, index) + (add || "") + this.slice(index + count);
            }


            Example:



             > "Held!".splice(3,0,"lo Worl")
            < "Hello World!"






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 23 '17 at 12:02









            Community

            11




            11










            answered Oct 17 '16 at 19:12









            Mike Godin

            1,41111522




            1,41111522






















                up vote
                2
                down vote













                I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).



                String.prototype.splice = function(startIndex,length,insertString){
                return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
                };


                You can use it like this:



                var creditCardNumber = "5500000000000004";
                var cardSuffix = creditCardNumber.splice(0,12,'****');
                console.log(cardSuffix); // output: ****0004


                See Test Results:
                https://jsfiddle.net/0quz9q9m/5/






                share|improve this answer





















                • you should at least do ` + (insertString || "") + ` instead of ` + insertString + , otherwise the third argument is not optional. This implementation also doesn't take care of startIndex < 0` unlike other suggestions. Great example of usage, though
                  – YakovL
                  Nov 11 at 10:37

















                up vote
                2
                down vote













                I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).



                String.prototype.splice = function(startIndex,length,insertString){
                return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
                };


                You can use it like this:



                var creditCardNumber = "5500000000000004";
                var cardSuffix = creditCardNumber.splice(0,12,'****');
                console.log(cardSuffix); // output: ****0004


                See Test Results:
                https://jsfiddle.net/0quz9q9m/5/






                share|improve this answer





















                • you should at least do ` + (insertString || "") + ` instead of ` + insertString + , otherwise the third argument is not optional. This implementation also doesn't take care of startIndex < 0` unlike other suggestions. Great example of usage, though
                  – YakovL
                  Nov 11 at 10:37















                up vote
                2
                down vote










                up vote
                2
                down vote









                I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).



                String.prototype.splice = function(startIndex,length,insertString){
                return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
                };


                You can use it like this:



                var creditCardNumber = "5500000000000004";
                var cardSuffix = creditCardNumber.splice(0,12,'****');
                console.log(cardSuffix); // output: ****0004


                See Test Results:
                https://jsfiddle.net/0quz9q9m/5/






                share|improve this answer












                I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).



                String.prototype.splice = function(startIndex,length,insertString){
                return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
                };


                You can use it like this:



                var creditCardNumber = "5500000000000004";
                var cardSuffix = creditCardNumber.splice(0,12,'****');
                console.log(cardSuffix); // output: ****0004


                See Test Results:
                https://jsfiddle.net/0quz9q9m/5/







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Sep 5 '16 at 0:22









                Timothy Kanski

                1,374619




                1,374619












                • you should at least do ` + (insertString || "") + ` instead of ` + insertString + , otherwise the third argument is not optional. This implementation also doesn't take care of startIndex < 0` unlike other suggestions. Great example of usage, though
                  – YakovL
                  Nov 11 at 10:37




















                • you should at least do ` + (insertString || "") + ` instead of ` + insertString + , otherwise the third argument is not optional. This implementation also doesn't take care of startIndex < 0` unlike other suggestions. Great example of usage, though
                  – YakovL
                  Nov 11 at 10:37


















                you should at least do ` + (insertString || "") + ` instead of ` + insertString + , otherwise the third argument is not optional. This implementation also doesn't take care of startIndex < 0` unlike other suggestions. Great example of usage, though
                – YakovL
                Nov 11 at 10:37






                you should at least do ` + (insertString || "") + ` instead of ` + insertString + , otherwise the third argument is not optional. This implementation also doesn't take care of startIndex < 0` unlike other suggestions. Great example of usage, though
                – YakovL
                Nov 11 at 10:37












                up vote
                2
                down vote













                Simply use substr for string



                ex.



                var str = "Hello world!";
                var res = str.substr(1, str.length);


                Result = ello world!






                share|improve this answer

























                  up vote
                  2
                  down vote













                  Simply use substr for string



                  ex.



                  var str = "Hello world!";
                  var res = str.substr(1, str.length);


                  Result = ello world!






                  share|improve this answer























                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    Simply use substr for string



                    ex.



                    var str = "Hello world!";
                    var res = str.substr(1, str.length);


                    Result = ello world!






                    share|improve this answer












                    Simply use substr for string



                    ex.



                    var str = "Hello world!";
                    var res = str.substr(1, str.length);


                    Result = ello world!







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Oct 19 '16 at 12:56









                    Dinesh Patil

                    40936




                    40936






















                        up vote
                        0
                        down vote













                        There seem to be a lot of confusion which was addressed only in comments by elclanrs and raina77ow, so let me post a clarifying answer.



                        Clarification



                        From "string.splice" one may expect that it, like the one for arrays:




                        • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

                        • returns the cut out part

                        • modifies the original string


                        The problem is, the 3d requirement can not be fulfilled because strings are immutable (related: 1, 2), I've found the most dedicated comment here:




                        In JavaScript strings are primitive value types and not objects (spec). In fact, as of ES5, they're one of the only 5 value types alongside null, undefined, number and boolean. Strings are assigned by value and not by reference and are passed as such. Thus, strings are not just immutable, they are a value. Changing the string "hello" to be "world" is like deciding that from now on the number 3 is the number 4... it makes no sense.




                        So, with that in account, one may expect the "string.splice" thing to only:




                        • accepts up to 2 arguments: start position, length (insertion makes no sense since the string is not changed)

                        • returns the cut out part


                        which is what substr does; or, alternatively,




                        • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

                        • returns the modified string (without the cut part and with insertion)


                        which is the subject of the next section.



                        Solutions



                        If you care about optimizing, you should probably use the Mike's implementation:



                        String.prototype.splice = function(index, count, add) {
                        if (index < 0) {
                        index += this.length;
                        if (index < 0)
                        index = 0;
                        }
                        return this.slice(0, index) + (add || "") + this.slice(index + count);
                        }


                        Treating the out-of-boundaries index may vary, though. Depending on your needs, you may want:



                            if (index < 0) {
                        index += this.length;
                        if (index < 0)
                        index = 0;
                        }
                        if (index >= this.length) {
                        index -= this.length;
                        if (index >= this.length)
                        index = this.length - 1;
                        }


                        or even



                            index = index % this.length;
                        if (index < 0)
                        index = this.length + index;


                        If you don't care about performance, you may want to adapt Kumar's suggestion which is more straight-forward:



                        String.prototype.splice = function(index, count, add) {
                        var chars = this.split('');
                        chars.splice(index, count, add);
                        return chars.join('');
                        }


                        Performance



                        The difference in performances increases drastically with the length of the string. jsperf shows, that for strings with the length of 10 the latter solution (splitting & joining) is twice slower than the former solution (using slice), for 100-letter strings it's x5 and for 1000-letter strings it's x50, in Ops/sec it's:



                                              10 letters   100 letters   1000 letters
                        slice implementation 1.25 M 2.00 M 1.91 M
                        split implementation 0.63 M 0.22 M 0.04 M


                        note that I've changed the 1st and 2d arguments when moving from 10 letters to 100 letters (still I'm surprised that the test for 100 letters runs faster than that for 10 letters).






                        share|improve this answer



























                          up vote
                          0
                          down vote













                          There seem to be a lot of confusion which was addressed only in comments by elclanrs and raina77ow, so let me post a clarifying answer.



                          Clarification



                          From "string.splice" one may expect that it, like the one for arrays:




                          • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

                          • returns the cut out part

                          • modifies the original string


                          The problem is, the 3d requirement can not be fulfilled because strings are immutable (related: 1, 2), I've found the most dedicated comment here:




                          In JavaScript strings are primitive value types and not objects (spec). In fact, as of ES5, they're one of the only 5 value types alongside null, undefined, number and boolean. Strings are assigned by value and not by reference and are passed as such. Thus, strings are not just immutable, they are a value. Changing the string "hello" to be "world" is like deciding that from now on the number 3 is the number 4... it makes no sense.




                          So, with that in account, one may expect the "string.splice" thing to only:




                          • accepts up to 2 arguments: start position, length (insertion makes no sense since the string is not changed)

                          • returns the cut out part


                          which is what substr does; or, alternatively,




                          • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

                          • returns the modified string (without the cut part and with insertion)


                          which is the subject of the next section.



                          Solutions



                          If you care about optimizing, you should probably use the Mike's implementation:



                          String.prototype.splice = function(index, count, add) {
                          if (index < 0) {
                          index += this.length;
                          if (index < 0)
                          index = 0;
                          }
                          return this.slice(0, index) + (add || "") + this.slice(index + count);
                          }


                          Treating the out-of-boundaries index may vary, though. Depending on your needs, you may want:



                              if (index < 0) {
                          index += this.length;
                          if (index < 0)
                          index = 0;
                          }
                          if (index >= this.length) {
                          index -= this.length;
                          if (index >= this.length)
                          index = this.length - 1;
                          }


                          or even



                              index = index % this.length;
                          if (index < 0)
                          index = this.length + index;


                          If you don't care about performance, you may want to adapt Kumar's suggestion which is more straight-forward:



                          String.prototype.splice = function(index, count, add) {
                          var chars = this.split('');
                          chars.splice(index, count, add);
                          return chars.join('');
                          }


                          Performance



                          The difference in performances increases drastically with the length of the string. jsperf shows, that for strings with the length of 10 the latter solution (splitting & joining) is twice slower than the former solution (using slice), for 100-letter strings it's x5 and for 1000-letter strings it's x50, in Ops/sec it's:



                                                10 letters   100 letters   1000 letters
                          slice implementation 1.25 M 2.00 M 1.91 M
                          split implementation 0.63 M 0.22 M 0.04 M


                          note that I've changed the 1st and 2d arguments when moving from 10 letters to 100 letters (still I'm surprised that the test for 100 letters runs faster than that for 10 letters).






                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            There seem to be a lot of confusion which was addressed only in comments by elclanrs and raina77ow, so let me post a clarifying answer.



                            Clarification



                            From "string.splice" one may expect that it, like the one for arrays:




                            • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

                            • returns the cut out part

                            • modifies the original string


                            The problem is, the 3d requirement can not be fulfilled because strings are immutable (related: 1, 2), I've found the most dedicated comment here:




                            In JavaScript strings are primitive value types and not objects (spec). In fact, as of ES5, they're one of the only 5 value types alongside null, undefined, number and boolean. Strings are assigned by value and not by reference and are passed as such. Thus, strings are not just immutable, they are a value. Changing the string "hello" to be "world" is like deciding that from now on the number 3 is the number 4... it makes no sense.




                            So, with that in account, one may expect the "string.splice" thing to only:




                            • accepts up to 2 arguments: start position, length (insertion makes no sense since the string is not changed)

                            • returns the cut out part


                            which is what substr does; or, alternatively,




                            • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

                            • returns the modified string (without the cut part and with insertion)


                            which is the subject of the next section.



                            Solutions



                            If you care about optimizing, you should probably use the Mike's implementation:



                            String.prototype.splice = function(index, count, add) {
                            if (index < 0) {
                            index += this.length;
                            if (index < 0)
                            index = 0;
                            }
                            return this.slice(0, index) + (add || "") + this.slice(index + count);
                            }


                            Treating the out-of-boundaries index may vary, though. Depending on your needs, you may want:



                                if (index < 0) {
                            index += this.length;
                            if (index < 0)
                            index = 0;
                            }
                            if (index >= this.length) {
                            index -= this.length;
                            if (index >= this.length)
                            index = this.length - 1;
                            }


                            or even



                                index = index % this.length;
                            if (index < 0)
                            index = this.length + index;


                            If you don't care about performance, you may want to adapt Kumar's suggestion which is more straight-forward:



                            String.prototype.splice = function(index, count, add) {
                            var chars = this.split('');
                            chars.splice(index, count, add);
                            return chars.join('');
                            }


                            Performance



                            The difference in performances increases drastically with the length of the string. jsperf shows, that for strings with the length of 10 the latter solution (splitting & joining) is twice slower than the former solution (using slice), for 100-letter strings it's x5 and for 1000-letter strings it's x50, in Ops/sec it's:



                                                  10 letters   100 letters   1000 letters
                            slice implementation 1.25 M 2.00 M 1.91 M
                            split implementation 0.63 M 0.22 M 0.04 M


                            note that I've changed the 1st and 2d arguments when moving from 10 letters to 100 letters (still I'm surprised that the test for 100 letters runs faster than that for 10 letters).






                            share|improve this answer














                            There seem to be a lot of confusion which was addressed only in comments by elclanrs and raina77ow, so let me post a clarifying answer.



                            Clarification



                            From "string.splice" one may expect that it, like the one for arrays:




                            • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

                            • returns the cut out part

                            • modifies the original string


                            The problem is, the 3d requirement can not be fulfilled because strings are immutable (related: 1, 2), I've found the most dedicated comment here:




                            In JavaScript strings are primitive value types and not objects (spec). In fact, as of ES5, they're one of the only 5 value types alongside null, undefined, number and boolean. Strings are assigned by value and not by reference and are passed as such. Thus, strings are not just immutable, they are a value. Changing the string "hello" to be "world" is like deciding that from now on the number 3 is the number 4... it makes no sense.




                            So, with that in account, one may expect the "string.splice" thing to only:




                            • accepts up to 2 arguments: start position, length (insertion makes no sense since the string is not changed)

                            • returns the cut out part


                            which is what substr does; or, alternatively,




                            • accepts up to 3 arguments: start position, length and (optionally) insertion (string)

                            • returns the modified string (without the cut part and with insertion)


                            which is the subject of the next section.



                            Solutions



                            If you care about optimizing, you should probably use the Mike's implementation:



                            String.prototype.splice = function(index, count, add) {
                            if (index < 0) {
                            index += this.length;
                            if (index < 0)
                            index = 0;
                            }
                            return this.slice(0, index) + (add || "") + this.slice(index + count);
                            }


                            Treating the out-of-boundaries index may vary, though. Depending on your needs, you may want:



                                if (index < 0) {
                            index += this.length;
                            if (index < 0)
                            index = 0;
                            }
                            if (index >= this.length) {
                            index -= this.length;
                            if (index >= this.length)
                            index = this.length - 1;
                            }


                            or even



                                index = index % this.length;
                            if (index < 0)
                            index = this.length + index;


                            If you don't care about performance, you may want to adapt Kumar's suggestion which is more straight-forward:



                            String.prototype.splice = function(index, count, add) {
                            var chars = this.split('');
                            chars.splice(index, count, add);
                            return chars.join('');
                            }


                            Performance



                            The difference in performances increases drastically with the length of the string. jsperf shows, that for strings with the length of 10 the latter solution (splitting & joining) is twice slower than the former solution (using slice), for 100-letter strings it's x5 and for 1000-letter strings it's x50, in Ops/sec it's:



                                                  10 letters   100 letters   1000 letters
                            slice implementation 1.25 M 2.00 M 1.91 M
                            split implementation 0.63 M 0.22 M 0.04 M


                            note that I've changed the 1st and 2d arguments when moving from 10 letters to 100 letters (still I'm surprised that the test for 100 letters runs faster than that for 10 letters).







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 11 at 11:23

























                            answered Nov 10 at 13:49









                            YakovL

                            2,841102338




                            2,841102338






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20817618%2fis-there-a-splice-method-for-strings%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Tangent Lines Diagram Along Smooth Curve

                                Yusuf al-Mu'taman ibn Hud

                                Zucchini