Removes characters from a string and inserts another in their place, following Array.prototype.splice.
It is the short form of the round trip most code writes by hand, without the intermediate array:
const chars = str.split(''); chars.splice(2, 2, 'X', 'Y'); const result = chars.join('');
Syntax
import { stringSplice } from '@opentf/std'; stringSplice( str: string, start?: number, deleteCount?: number, insert?: string ): string;
Default start = 0, insert = ''. Omitting deleteCount removes everything from start onwards.
start must be a finite integer, and deleteCount a non-negative finite integer. A negative start counts back from the end of the string.
Indices count UTF-16 code units, the same as String.prototype.slice and indexOf, so a position taken from either — or from a textarea's selectionStart — can be passed straight in. A boundary landing inside a surrogate pair is widened to cover the whole character, so the result never contains a lone surrogate, unlike split(''), which cuts an emoji in half.
Examples
Replacing a range:
stringSplice('2026-07-30', 5, 2, '08'); //=> '2026-08-30' stringSplice('v1.4.0', 3, 1, '5'); //=> 'v1.5.0'
The replacement need not be the length of what it removes, which is what makes masking and eliding work:
stringSplice('4111111111111111', 4, 8, '••••'); //=> '4111••••1111' stringSplice('/home/ada/projects/std/src/index.ts', 6, 20, '…'); //=> '/home/…/index.ts'
Inserting, by removing nothing:
stringSplice('SELECT * FROM users', 19, 0, ' LIMIT 10'); //=> 'SELECT * FROM users LIMIT 10' // At the caret of a textarea. stringSplice(el.value, el.selectionStart, 0, '\t');
Deleting, by inserting nothing:
stringSplice('2026-07-30T09:15:00Z', -1); //=> '2026-07-30T09:15:00' // Everything from an index onwards, here dropping a query string. const url = 'https://example.com/search?q=std&page=2'; stringSplice(url, url.indexOf('?')); //=> 'https://example.com/search'
Counting back from the end:
stringSplice('report.txt', -3, 3, 'csv'); //=> 'report.csv'
Multi code unit characters are removed whole, never split:
stringSplice('Ship it 🚀', 8, 1, 'now'); //=> 'Ship it now' stringSplice('😀😃😄😁', 2, 2, '😎'); //=> '😀😎😄😁'
Related
stringReplace — replaces by pattern rather than by position.