Remove, replace, or insert a part of a String, Number, or Array.
Syntax
Parameters
subject
- The entity to splice.start
and length
parameters will be removed, if applicable.start
and length
parameters will be removed, if applicable. Numeric keys will be re-ordered.start
- The position to start splicing at. If start
is non-negative, the position will be calculated from the beginning of subject
, otherwise it will be calculated from the end.length
- The number of elements (characters in a String, or items in an Array) to remove. If omitted, everything from start
to the end of subject
will be removed. If non-negative, the sequence will contain that many elements, otherwise if negative, the sequence will stop that many elements from the end of subject
.newpart
- The data supplied will be inserted into subject
at position start
, after optionally removing elements as specified by length
.
Result
subject
.
Removes a sequence from subject
, defined by start
and length
. If length is 0
, nothing is removed. Any data in newpart
is then inserted at start
. If length is 0
then this is essentially an insertion, otherwise it is a replacement. The resulting subject
is then returned.
If data is being removed, and needs to be retained, slice()
should be used first.
Common uses, and equivalents in other languages | ||
---|---|---|
Description | Example code | Equivalent |
Add one item to the end of an Array | splice(subject, length(subject), 0, a) | push |
Add one item to the end of an Array | splice(subject, length(subject), 0, @a) | push |
Add one item to the end of an Array | splice(subject, length(subject), 0, [a]) | push |
Add more than one item to the end of an Array | splice(subject, length(subject), 0, [a, b, c]) | push |
Remove one item from the end of an Array | splice(subject, -1) | pop |
Add one item to the start of an Array | splice(subject, 0, 0, a) | unshift |
Add one item to the start of an Array | splice(subject, 0, 0, @a) | unshift |
Add one item to the start of an Array | splice(subject, 0, 0, [a]) | unshift |
Add more than one item to the start of an Array | splice(subject, 0, 0, [a, b, c]) | unshift |
Remove one item from the start of an Array | splice(subject, 0, 1) | shift |
Alternatives to using splice() |
|
---|---|
Example code | Alternative code |
splice(subject, length(subject), 0, a) | subject[] = a |
splice(subject, x, 1, a) | subject[x] = a |
splice(subject, x, 1, @a) | subject[x] = a |
splice(subject, x, 1, [a]) | subject[x] = a |
splice(subject, x, 1) | destroy subject[x] |
Note that in the tables above, the returned value from splice()
is not equivalent to the returned value from similar functions in other languages. The tables focus on the effect the methods have on subject
. splice()
will always return the modified subject
, and not any items that may have been removed.