substring,slice,substr

这是JavaScript 权威指南上的说明,象我这种E文很烂的就能勉强看懂一下,并没有对着翻译,只是按照理解说明了下。



string.substring(from, to)
Arguments

from

A nonnegative integer that specifies the position within string of the first character of the desired substring.

       指定想要得到字符串的开始位置,即索引(非负整数)

to

A nonnegative optional integer that is one greater than the position of the last character of the desired substring. If this argument is omitted, the returned substring runs to the end of the string.

       指定想要得到字符串的结束位置,不包括该位置的字符(非负整数,可选,没有指定则返回从指定开始位置到原字符串结束位置)




string.slice(start, end)
Arguments

start

The string index where the slice is to begin. If negative, this argument specifies a position measured from the end of the string. That is, -1 indicates the last character, -2 indicates the second from last character, and so on.

        指定想要得到字符串的开始的位置,即索引。

end

The string index immediately after the end of the slice. If not specified, the slice includes all characters from start to the end of the string. If this argument is negative, it specifies a position measured from the end of the string.

        指定想要得到字符串的结束位置,不包括该位置的字符(可选,没有指定则返回从指定开始位置到原字符串结束位置)


string.substr(start, length)

Arguments

start

The start position of the substring. If this argument is negative, it specifies a position measured from the end of the string: -1 specifies the last character, -2 specifies the second-to-last character, and so on.

        指定想要得到字符串的开始的位置,即索引。

length

The number of characters in the substring. If this argument is omitted, the returned substring includes all characters from the starting position to the end of the string.

        指定想要得到字符串的长度,(可选,没有指定则返回从指定开始位置到原字符串结束位置)




PS:这三个方法均返回截取原字符串的一部分新字符串,第2个参数均为可选参数,并且其实所有的参数均可以为负整数。

string.substring(from, to)
string.slice(start, end)

这两个方法差不多,都是指定开始和结束位置返回新字符串,在参数均为正整数的时候返回结果一样,当参数为负整数的时候,string.substring(from, to) 把负整数都当作0处理,而 string.slice(start, end) 将把负整数加上该字符串的长度处理。

string.substr(start, length)

这个方法只在第二个参数上指定的是新字符串的长度,对于负正数和string.slice(start, end)处理一样,把负整数加上原字符串的长度。

Example

var s = "abcdefg";

s.substring(1,4) // Returns "bcd"
s.slice(1,4) // Returns "bcd"
s.substr(1,4) // Returns "bcde"

s.substring(2,-3) // Returns "ab" 实际上是 s.substring(0,2) 较小的参数会在前面
s.slice(2,-3) // Returns "cd" 实际上是 s.slice(2,4)
s.substr(2,-3) // Returns "cdef" 实际上是 s.slice(2,4)


原文地址:https://www.cnblogs.com/qieqing/p/1225820.html