Design & Download
Your JS Library
in Seconds!!!

Snippet: splice()

Written by Christopher West (cwest) on January 12, 2016.
Duplicates an array or a string and adds and/or removes one or more values from it.
function splice(arrOrStr, start, opt_length, opt_replacement) {
  opt_length = opt_length != undefined
    ? opt_length < 0
      ? arrOrStr.length - start + opt_length
      : opt_length
    : Infinity;
  start = start < 0 ? Math.max(0, arrOrStr.length + start) : start;
  if (isArrayLike(arrOrStr)) {
    return slice(arrOrStr, 0, start).concat(opt_replacement || [], slice(arrOrStr, start + opt_length));
  }
  return arrOrStr.slice(0, start)
    + (opt_replacement === undefined ? '' : opt_replacement)
    + arrOrStr.slice(start + opt_length);
}

splice(...) API Documentation

Duplicates an array or a string and adds and/or removes one or more values from it. NOTE: This is different from the traditional splice function because it doesn't modify the array, but rather it returns a modified duplicate.

Parameters

  1. arrOrStr {Array|string}:
    The array or string to be duplicated and modified.
  2. start {number}:
    The index at which to start modifying arrOrStr. If this number is negative the index will be calculated from the end of arrOrStr.
  3. opt_length {number=}:
    Optional. Defaults to Infinity. Indicates the amount of indices that should be removed from arrOrStr. If negative this will be used as if it were an index counting from the end of arrOrStr.
  4. opt_replacement {Array|string}:
    Optional. If specified, this will be inserted at start. If arrOrStr is an array, this should be an array of the values to insert at start. If arrOrStr is a string, this should be the string to insert at start.

Returns

The modified duplicate of arrOrStr.