stringSplice

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:

TypeScript
const chars = str.split('');
chars.splice(2, 2, 'X', 'Y');
const result = chars.join('');

Syntax

TypeScript
import { stringSplice } from '@opentf/std';
stringSplice(str: string, start?: number, options?: { deleteCount?: number; insert?: string }): string;
Info

Default start = 0, insert = ''. Omitting deleteCount removes everything from start onwards.

Info

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:

TypeScript
stringSplice('2026-07-30', 5, { deleteCount: 2, insert: '08' }); //=> '2026-08-30'

stringSplice('v1.4.0', 3, { deleteCount: 1, insert: '5' }); //=> 'v1.5.0'

The replacement need not be the length of what it removes, which is what makes masking and eliding work:

TypeScript
stringSplice('4111111111111111', 4, { deleteCount: 8, insert: '••••' }); //=> '4111••••1111'

stringSplice('/home/ada/projects/std/src/index.ts', 6, { deleteCount: 20, insert: '…' });
//=> '/home/…/index.ts'

Inserting, by removing nothing:

TypeScript
stringSplice('SELECT * FROM users', 19, { deleteCount: 0, insert: ' LIMIT 10' });
//=> 'SELECT * FROM users LIMIT 10'

// At the caret of a textarea.
const el = { value: 'SELECT *', selectionStart: 6 };
stringSplice(el.value, el.selectionStart, { deleteCount: 0, insert: '\t' });

Deleting, by inserting nothing:

TypeScript
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:

TypeScript
stringSplice('report.txt', -3, { deleteCount: 3, insert: 'csv' }); //=> 'report.csv'

Multi code unit characters are removed whole, never split:

TypeScript
stringSplice('Ship it 🚀', 8, { deleteCount: 1, insert: 'now' }); //=> 'Ship it now'

stringSplice('😀😃😄😁', 2, { deleteCount: 2, insert: '😎' }); //=> '😀😎😄😁'

Try it

Last updated on
Edit this page