javascript——slice与substring区别

stringObject.slice(startIndex,endIndex)

  返回字符串 stringObject 从 startIndex 开始(包括 startIndex )到 endIndex 结束(不包括 endIndex )为止的所有字符。

字符串中第一个字符的位置是从【0】开始的,最后一个字符的位置为【stringObject.length-1】,所以slice()方法返回的字符串不包括endIndex位置的字符。

①。参数为空或0都返回-------------stringObject的全部

②。参数为负数,则从最后一个(-1)算起

③。两个参数相等则返回-------------空串

④。同号时(都为正数,或都为负数时)如果endIndex>sartIndex----------空串

⑤。异号时如果负数从后往前数,正数从前往后数。截取sartIndex以后endIndex以前的数据。

如果没有交集则返回---------------------空串

如果有交集则----------------------------交集即结果。(!!!!!!)

⑥参数 endIndex 可选,如果没有指定,则默认为字符串的长度 stringObject.length 。

 

 

stringObject.substring(startIndex、endIndex)

  返回字符串 stringObject 从 startIndex 开始(包括 startIndex )到 endIndex 结束(不包括 endIndex )为止的所有字符。

字符串中第一个字符的位置是从【0】开始的,最后一个字符的位置为【stringObject.length-1】,所以substring()方法返回的字符串不包括endIndex位置的字符。

 

①。参数为空或0或(负数先转换成0)都返回-------------stringObject的全部

②。参数为负数先转换成0

③。两个参数相等则返回-------------空串

④。非负情况下,如果endIndex>sartIndex----------substring(startIndex、endIndex)=substring(endIndex,startIndex)

⑤参数 endIndex 可选,如果没有指定,则默认为字符串的长度 stringObject.length 。 

 

 

例子:

var sMyString = "Tsinghua University";

 

document.write(sMyString.slice(0) + "<br>");     //Tsinghua University
document.write(sMyString.substring(0) + "<br>"); //Tsinghua University

document.write(sMyString.slice() + "<br>");     //Tsinghua University
document.write(sMyString.substring() + "<br>"); //Tsinghua University


document.write(sMyString.slice(-1) + "<br>");       //y
document.write(sMyString.substring(-1) + "<br>");   //=substring(0)=Tsinghua University

 

document.write(sMyString.slice(1,3) + "<br>");      //si
document.write(sMyString.slice(3,1) + "<br>");      //空串

 

 

document.write(sMyString.slice(4) + "<br>");        //ghua University
document.write(sMyString.substring(4) + "<br>");    //ghua University

document.write(sMyString + "<br>");                 //不改变原字符串

 

 

 


document.write(sMyString.slice(-3,-1) + "<br>");    //it
document.write(sMyString.slice(-1,-3) + "<br>");    //空串

document.write(sMyString.slice(-15,15) + "<br>");//slice(-15,15):g(-15)hua Univer(15)!!!!!!

document.write(sMyString.slice(2,-3) + "<br>");

//inghua Univers负数从后往前数,正数从前往后数。截取sartIndex以后endIndex以前的数据

 


document.write(sMyString.substring(1,3) + "<br>");  //si
document.write(sMyString.substring(-1,-3) + "<br>");//空串=负数先转换成0即substring(0,0)=空
document.write(sMyString.substring(1,-3) + "<br>"); //T=负数先转换成0即substring(1,0)=T
document.write(sMyString.substring(3,1) + "<br>");  //si
document.write(sMyString.substring(-3,-1) + "<br>");//空串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值