Javascript substr 和 substring 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3745515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:58:29  来源:igfitidea点击:

What is the difference between substr and substring?

javascriptsubstring

提问by Difference Engine

What is the difference between

之间有什么区别

alert("abc".substr(0,2));

and

alert("abc".substring(0,2));

They both seem to output “ab”.

他们似乎都输出“ab”。

回答by Delan Azabani

The difference is in the second argument. The second argument to substringis the index to stop at (but not include), but the second argument to substris the maximum length to return.

不同之处在于第二个参数。to的第二个参数substring是要停止的索引(但不包括),但第二个参数substr是要返回的最大长度。

Links?

链接?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

回答by Colin Hebert

substring(MDN) takes parameters as (from, to).
substr(MDN) takes parameters as (from, length).

substring( MDN) 将参数作为(from, to).
substr( MDN) 将参数作为(from, length).

Update: MDN considers substrlegacy.

更新:MDN 考虑substr遗留问题。

alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"

You can remember substringtakes indices, as does yet another string extraction method, slice.

您可以记住substring采用索引,就像另一种字符串提取方法slice 一样

When starting from 0 you can use either method.

当从 0 开始时,您可以使用任何一种方法。

回答by JefferMC

As hinted at in yatima2975's answer, there is an additional difference:

正如 yatima2975 的回答所暗示的那样,还有一个额外的区别:

substr()accepts a negative starting position as an offset from the end of the string. substring()does not.

substr()接受负的起始位置作为距字符串末尾的偏移量。 substring()才不是。

From MDN:

来自MDN

If start is negative, substr() uses it as a character index from the end of the string.

如果 start 为负,则 substr() 将其用作从字符串末尾开始的字符索引。

So to sum up the functional differences:

所以总结一下功能上的区别:

substring(begin-offset, end-offset-exclusive)where begin-offset is 0or greater

substring(begin-offset, end-offset-exclusive)其中开始偏移是0或更大

substr(begin-offset, length)where begin-offset may also be negative

substr(begin-offset, length)其中开始偏移也可能为负

回答by yatima2975

Another gotcha I recently came across is that in IE 8, "abcd".substr(-1)erroneously returns "abcd", whereas Firefox 3.6 returns "d"as it should. sliceworks correctly on both.

我最近遇到的另一个问题是,在 IE 8 中,"abcd".substr(-1)错误地返回"abcd",而 Firefox 3.6 则正常返回"d"slice两者都能正常工作。

More on this topic can be found here.

可以在此处找到有关此主题的更多信息

回答by Nate Lipp

The main difference is that

主要区别在于

substr() allows you to specify the maximum length to return

substr() 允许您指定要返回的最大长度

substring() allows you to specify the indices and the second argument is NOT inclusive

substring() 允许您指定索引,第二个参数不包含

There are some additional subtleties between substr() and substring() such as the handling of equal arguments and negative arguments. Also note substring() and slice() are similar but not always the same.

substr() 和 substring() 之间还有一些额外的微妙之处,例如处理相等参数和否定参数。另请注意 substring() 和 slice() 相似但并不总是相同。

  //*** length vs indices:
    "string".substring(2,4);  // "ri"   (start, end) indices / second value is NOT inclusive
    "string".substr(2,4);     // "ring" (start, length) length is the maximum length to return
    "string".slice(2,4);      // "ri"   (start, end) indices / second value is NOT inclusive

  //*** watch out for substring swap:
    "string".substring(3,2);  // "r"    (swaps the larger and the smaller number)
    "string".substr(3,2);     // "in"
    "string".slice(3,2);      // ""     (just returns "")

  //*** negative second argument:
    "string".substring(2,-4); // "st"   (converts negative numbers to 0, then swaps first and second position)
    "string".substr(2,-4);    // ""
    "string".slice(2,-4);     // ""

  //*** negative first argument:
    "string".substring(-3);   // "string"        
    "string".substr(-3);      // "ing"  (read from end of string)
    "string".slice(-3);       // "ing"        

回答by CurnalCurz

The difference is second parameter. Their second parameters, while both numbers, are expecting two different things:

不同之处在于第二个参数。他们的第二个参数,虽然两个数字,都期待两个不同的东西:

When using substring the second parameter is the first index not to include:

使用子字符串时,第二个参数是第一个不包含的索引:

var s = "string";
s.substring(1, 3); // would return 'tr'

var s = "another example";
s.substring(3, 7); // would return 'ther'

When using substr the second parameter is the number of characters to include in the substring:

使用 substr 时,第二个参数是要包含在子字符串中的字符数:

var s = "string";
s.substr(1, 3); // would return 'tri'

var s = "another example";
s.substr(3, 7); // would return 'ther ex'

回答by 5ervant

The big difference is, substr()is a deprecated methodthat can still be used, but should be used with caution because they are expected to be removed entirely sometime in the future. You should work to remove their use from your code. And the substring()method succeeded and specified the former one.

最大的区别是,substr()一种仍然可以使用的已弃用方法,但应谨慎使用,因为预计它们将在将来的某个时候完全删除。您应该努力从您的代码中删除它们的使用。并且该substring()方法成功并指定了前一种。

回答by Ali007

Slice vs Substr vs Substring vs [ ] Methods

Slice vs Substr vs Substring vs [] 方法

There are performance benefits to each of these javascript methods. Please use these functions accordingly.

这些 javascript 方法中的每一个都有性能优势。请相应地使用这些功能。

回答by raju poloju

substring():It has 2 parameters "start" and "end".

substring():它有两个参数“start”和“end”。

  • startparameter is required and specifies the position where to start the extraction.
  • endparameter is optional and specifies the position where the extraction should end.
  • start参数是必需的,它指定开始提取的位置。
  • end参数是可选的,它指定提取结束的位置。

If the end parameter is not specified, all the characters from the start position till the end of the string are extracted.

如果不指定结束参数,则提取从开始位置到字符串结尾的所有字符。

var str = "Substring Example";
var result = str.substring(0, 10);
alert(result);

Output : Substring

If the value of start parameter is greater than the value of the end parameter, this method will swap the two arguments. This means start will be used as end and end will be used as start.

如果 start 参数的值大于 end 参数的值,则此方法将交换两个参数。这意味着开始将用作结束,结束将用作开始。

var str = "Substring Example";
var result = str.substring(10, 0);
alert(result);

Output : Substring

substr(): It has 2 parameters "start" and "count".

substr():它有两个参数“start”和“count”。

  • start parameter is required and specifies the position where to start the extraction.

  • count parameter is optional and specifies the number of characters to extract.

  • start 参数是必需的,它指定开始提取的位置。

  • count 参数是可选的,它指定要提取的字符数。

var str = "Substr Example";
var result = str.substr(0, 10);
alert(result);


Output : Substr Exa

If the count parameter is not specified, all the characters from the start position till the end of the string are extracted. If count is 0 or negative, an empty string is returned.

如果未指定 count 参数,则提取从开始位置到字符串末尾的所有字符。如果计数为 0 或负数,则返回空字符串。

var str = "Substr Example";
var result = str.substr(11);
alert(result);

Output : ple

回答by Sajith Mantharath

substring(startIndex, endIndex(not included))

子字符串(开始索引,结束索引(不包括))

substr(startIndex, how many characters)

substr(startIndex, 多少个字符)

const string = 'JavaScript';

console.log('substring(1,2)', string.substring(1,2)); // a
console.log('substr(1,2)', string.substr(1,2)); // av