Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

String.prototype.substr()

概述

substr() 方法返回字符串中从指定位置开始到指定长度的子字符串。

语法

str.substr(start[, length])

参数

start
开始提取字符的位置。如果为负值,则被看作 strLength + start,其中 strLength 为字符串的长度(例如,如果 start-3,则被看作 strLength-3)。
length
可选。提取的字符数。

描述

start 是一个字符的索引。首字符的索引为 0,最后一个字符的索引为 字符串的长度减去1。substrstart 位置开始提取字符,提取 length 个字符(或直到字符串的末尾)。

如果 start 为正值,且大于或等于字符串的长度,则 substr 返回一个空字符串。

如果 start 为负值,则 substr 把它作为从字符串末尾开始的一个字符索引。如果 start 为负值且 abs(start) 大于字符串的长度,则 substr 使用 0 作为开始提取的索引。注意负的 start 参数不被 Microsoft JScript 所支持。

如果 length 为 0 或负值,则 substr 返回一个空字符串。如果忽略 length,则 substr 提取字符,直到字符串末尾。

示例

例子:使用 substr

var str = "abcdefghij";

console.log("(1,2): "    + str.substr(1,2));   // (1,2): bc
console.log("(-3,2): "   + str.substr(-3,2));  // (-3,2): hi
console.log("(-3): "     + str.substr(-3));    // (-3): hij
console.log("(1): "      + str.substr(1));     // (1): bcdefghij
console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
console.log("(20, 2): "  + str.substr(20,2));  // (20, 2):

兼容旧环境(Polyfill)

Microsoft's JScript 不支持负的 start 索引。如果你想充分利用该方法的功能,则需要使用下面的兼容性代码修复此 bug:

// only run when the substr function is broken
if ('ab'.substr(-1) != 'b')
{
  /**
   *  Get the substring of a string
   *  @param  {integer}  start   where to start the substring
   *  @param  {integer}  length  how many characters to return
   *  @return {string}
   */
  String.prototype.substr = function(substr) {
    return function(start, length) {
      // did we get a negative start, calculate how much it is
      // from the beginning of the string
      if (start < 0) start = this.length + start;
      
      // call the original function
      return substr.call(this, start, length);
    }
  }(String.prototype.substr);
}

规范

Specification Status Comment
ECMAScript 3rd Edition. Standard Defined in the (informative) Compatibility Annex B.
Implemented in JavaScript 1.0
ECMAScript 5.1 (ECMA-262)
String.prototype.substr
Standard Defined in the (informative) Compatibility Annex B
ECMAScript 2015 (6th Edition, ECMA-262)
String.prototype.substr
Standard Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

Note: Up to version 3.6, Firefox had a bug which caused substr to return empty result when an explicit undefined value was passed in as the length.

相关链接

文档标签和贡献者

 此页面的贡献者: helloguangxue, AlexChao
 最后编辑者: helloguangxue,