javascript——slice与substring区别

来源:互联网 发布:java完全自学宝典 pdf 编辑:程序博客网 时间:2024/05/16 08:44

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>");//空串