Search code examples
javascripthtmlstringjoinsplice

Why can I not insert a substring into an array using splice()?


Excuse the petty question, but this is really nagging me. I'm following the mozilla example: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice Can someone explain why this doesn't work:

<body>
  <p id="test">
  </p>
</body>

var url = "teststring";

document.getElementById("test").innerHTML = (url.split('').splice(2,0,"teststring").join(''));

jsFiddle: https://jsfiddle.net/uyk2p437/1/


Solution

  • The Array#splice method returns an array containing removed elements, in your case, it would be empty and you are applying Array#join method which generates an empty string.

    Use String#slice ( or String#substring) method instead :

    url.slice(0, 2) + "teststring" + url.slice(2)
    

    var url = "teststring";
    
    document.getElementById("test").innerHTML = url.slice(0, 2) + "1" + url.slice(2);
    <body>
      <p id="test">
      </p>
    </body>