substring() , slice() and substr()方法

JS中截取字符串中子串的三种方法substring() , slice() and substr().

在JS中,Javascript提供了两种截取字符串中子串的方法:

1.substring(str,end)

str是必须输入,必须是正值;

end是可选的必须是正值;

根据字面意思,str为截取的开始位置,字符串的第一个字符位置为0;end为截取的结束位置.

substring() 方法返回的子串包括 start 处的字符,但不包括 end 处的字符。

例子:

var str = "abcedf";

sub1 = str.substring(0,1)   //sub1 return "a";

sub2 = str.substring(1,3)  //sub2 return "bce";

sub3 = str.substring(2)    // sub3 return "cedf";

2.slice(str,end)

slice()方法的用法基本跟substring一致,但slice()的参数允许负值;

例子:

var tempStr = "abc.def";

sub1 = tempStr.slice(0,1)   //sub1 return "a";

sub2 = tempStr.slice(1,3)  //sub2 return "bc.";

sub3 = tempStr.slice(2)    // sub3 return "c.def";

sub4= tempStr.slice(-2)    // sub4 return "ef";

sub5 = tempStr.slice(-4,-1)    // sub5 return ".def";

ps:str必须比end小,否则返回空字符串;

3.substr(str,length)

str是必须输入,str允许为负值,用法跟slice()一样;

length是截取字符串的长度;

孜孜不倦,必能求索;风尘仆仆,终有归途。
原文地址:https://www.cnblogs.com/liyuspace/p/7705620.html