此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

String.prototype.substr()

Deprecated

Avoid using this feature in new projects. HTML wrapper methods exist only for backwards compatibility. Use DOM APIs to create elements instead. This feature may be a candidate for removal from web standards or browsers.

Consider using the following features instead: DOM.

String 值的 substr() 方法返回该字符串的一部分,从指定的索引开始,然后扩展到给定数量的字符。

备注:substr() 不属于 ECMAScript 主要规范——它在附件 B: Web 浏览器的附加 ECMAScript 功能中定义,这是非浏览器运行时的可选标准。因此,建议人们使用标准的 String.prototype.substring()String.prototype.slice() 方法,以便使他们的代码能够更好地、最大程度地跨平台。String.prototype.substring() 页面对这三种方法进行了一些比较。

尝试一下

const str = "Mozilla";

console.log(str.substr(1, 2));
// Expected output: "oz"

console.log(str.substr(2));
// Expected output: "zilla"

语法

js
substr(start)
substr(start, length)

参数

start

返回子字符串中要包含的第一个字符的索引。

length 可选

要提取的字符数。

返回值

一个包含给定字符串指定部分的新字符串。

描述

字符串的 substr() 方法从字符串中提取 length 字符,从 start 索引开始计数。

  • 如果 start >= str.length,则返回空字符串。
  • 如果 start < 0,则索引从字符串末尾开始计数。更准确地说,在这种情况下,子字符串从 max(start + str.length, 0) 开始。
  • 如果省略 start 或其值为 undefined,则将其视为 0
  • 如果省略 length 或其值为 undefined,或者如果 start + length >= str.length,则 substr() 会提取字符到字符串末尾。
  • 如果 length < 0,则返回空字符串。
  • 对于 startlengthNaN 被视为 0

尽管我们建议你避免使用 substr(),但是没有简单的方法可以将遗留代码中的 substr() 迁移到 slice()substring(),而无需为 substr() 编写一个 polyfill。例如,当 str = "01234", a = 1, l = -2 时,str.substr(a, l)str.slice(a, a + l)str.substring(a, a + l) 都有不同的结果——substr() 返回空字符串,slice() 返回 "123",而 substring() 返回 "0"。实际的重构路径取决于对 al 范围的了解。

示例

使用 substr()

js
const aString = "Mozilla";

console.log(aString.substr(0, 1)); // 'M'
console.log(aString.substr(1, 0)); // ''
console.log(aString.substr(-1, 1)); // 'a'
console.log(aString.substr(1, -1)); // ''
console.log(aString.substr(-3)); // 'lla'
console.log(aString.substr(1)); // 'ozilla'
console.log(aString.substr(-20, 2)); // 'Mo'
console.log(aString.substr(20, 2)); // ''

规范

规范
ECMAScript® 2027 Language Specification
# sec-string.prototype.substr

浏览器兼容性

参见