Oliver Klingefjord
Oliver Klingefjord

Reputation: 53

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/

Upvotes: 1

Views: 56

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115232

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>

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45135

Because the return value from splice is the removed items. Not the modified array. It modifies in place

As per MDN

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

var url = "teststring";
var split = url.split('');
split.splice(2,0,"teststring");   // this returns an empty array because you aren't removing anything
// but the value in split is now:
// ['t','e','t','e','s','t','s','t','r','i','n','g','s','t','s','t','r','i','n','g']
console.log(split.join(''));      // gives you the expected result

Or you can use slice as in Pranav's answer, or substr or substring.

Upvotes: 0

Related Questions