1

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/

5
  • 1
    what do you expect? Commented Feb 7, 2017 at 18:27
  • @MattBurland I think you meant splice not split. (5min already passed)! Commented Feb 7, 2017 at 18:33
  • @ibrahimmahrir: Whoops. Thanks. Commented Feb 7, 2017 at 18:35
  • because splice() doesn't return the Array you've spliced, but the array you've removed. In your case url.split('').slice(2,2).join('') would do exactly the same Commented Feb 7, 2017 at 18:38
  • jsfiddle.net/uyk2p437/2 Commented Feb 7, 2017 at 18:44

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

substr will be better since it's a string (I don't mean in performance or anything I just meant it would make sense)! But good answer anyway!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.