3

I understand I could and probably should use substring :)

For educational reasons, I want to know why I can't use call to do a splice operation on a string, which I understand to be an array-like object. It seems like this should work:

Array.prototype.splice.call('filename.jpg', -3, 3).join(''); // return the last three chars

Throws error TypeError: Object.isSealed called on non-object in V8.

SimplGy
  • 20,079
  • 15
  • 107
  • 144
  • 3
    Maybe because strings are immutable. *"which I understand to be an array-like object."* it's true that primitive values are converter to their object counterpart, but they are still immutable. – Felix Kling Jun 02 '14 at 03:50
  • Though I'm not sure where the error comes from. Firefox throws `TypeError: property Array.prototype.splice.call(...) is non-configurable and can't be deleted` which is even more obscure (since it doesn't look like we are deleting `Array.prototype.splice.call`). – Felix Kling Jun 02 '14 at 03:55
  • Array.prototype.splice.call(new String('filename.jpg'), -3, 3).join(''); – dandavis Jun 02 '14 at 05:12
  • @dandavis: What about it? FWIW, `.splice` already converts the `this` value to an object, so that's equivalent to passing a primitive string. – Felix Kling Jun 02 '14 at 05:17
  • @FelixKling: except a primitive string errors, so something is not equivalent... – dandavis Jun 02 '14 at 05:18
  • @dandavis: Ah, it doesn't error in Chrome, but it does in Firefox (same error). – Felix Kling Jun 02 '14 at 05:19
  • @FelixKling: i hate it when you're right almost as much as i hate it when FF and Chrome differ... – dandavis Jun 02 '14 at 05:22

2 Answers2

6

In Javascript, strings are immutable; they can't be changed after they're created. So there's no "set char" or "splice" methods because a string can't be changed. You can, however, call split('') on them to turn them into arrays, so you can use 'filename.jpg'.split('').splice(-3, 3).join('') for the same effect.

  • 2
    Thanks for the explanation, makes sense. Also explains why I can use `slice` directly, because it doesn't modify the original object. – SimplGy Jun 02 '14 at 04:00
2

You need to convert it to an array object first

Array.prototype.splice.call('filename.jpg'.split(''), -3, 3).join('');
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159