We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

substr() 方法返回一个字符串中从指定位置开始到指定字符数的字符。


str.substr(start[, length])


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


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


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);


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


We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

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.



最后编辑者: xybin1990,