setRangeText Edits Input Selections

HTMLInputElement.setRangeText replaces a character range with four selection modes, and omitting start and end targets the current user selection instead.

TypescriptForm Validation

Code

typescriptsnippet
15 lines
declare const input: HTMLInputElement;

// 完整签名:替换 [start, end) 并声明替换后的选区位置
input.setRangeText('REDACTED', 3, 7, 'select');
console.log('select keeps the replacement highlighted');

// 'start' / 'end' 把光标放到插入点前后;缺省 'preserve' 尽量保住原选区
input.setRangeText('-', 0, 0, 'end');
const mode: 'select' | 'start' | 'end' | 'preserve' = 'preserve';
input.setRangeText('x', 0, 1, mode);
console.log('selection mode union is closed:', mode);

// 只传替换串:范围取用户当前选区 selectionStart/selectionEnd
input.setRangeText('PASTED');
console.log(input.value);

Using it

The run emits 2 labeled sections — select keeps the replacement highlighted, selection mode union is closed: — one per step.

Output is labeled for readability — expect lines prefixed with select keeps the replacement highlighted, selection mode union is closed:.

Key statements

const mode: 'select' | 'start' | 'end' | 'preserve' = 'preserve';
input.setRangeText('REDACTED', 3, 7, 'select');
declare const input: HTMLInputElement;

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do.