大网数据广告活动
Web 标准与前端开发

HTMLInputElement: setRangeText() method

· 52CE 我爱测

The **`HTMLInputElement.setRangeText()`** method replaces a range of text in an input or textarea element with a new string.

HTML DOM

The HTMLInputElement.setRangeText() method replaces a range of text in an input or textarea element with a new string.

Syntax

setRangeText(replacement)
setRangeText(replacement, start)
setRangeText(replacement, start, end)
setRangeText(replacement, start, end, selectMode)

Parameters

  • replacement
    • : The string to insert.
  • start
    • : The 0-based index of the first character to replace. Defaults to the current selectionStart value (the start of the user's current selection).
  • end
    • : The 0-based index of the character after the last character to replace. Defaults to the current selectionEnd value (the end of the user's current selection).
  • selectMode
    • : A string defining how the selection should be set after the text has been replaced. Possible values:
      • "select" selects the newly inserted text.
      • "start" moves the selection to just before the inserted text.
      • "end" moves the selection to just after the inserted text.
      • "preserve" attempts to preserve the selection. This is the default.

Return value

None (undefined).

Examples

Click the button in this example to replace part of the text in the text box. The newly inserted text will be highlighted (selected) afterwards.

HTML

<input
  type="text"
  id="text-box"
  size="30"
  value="This text has NOT been updated." />
<button>Update text</button>

JavaScript

function selectText() {
  const input = document.getElementById("text-box");
  input.focus();
  input.setRangeText("ALREADY", 14, 17, "select");
}

document.querySelector("button").addEventListener("click", selectText);

Result

Examples

Specifications

Browser compatibility

See also

  • input
  • textarea
  • HTMLInputElement
  • Selection

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。