背景:
阅读新闻

JavaScript slice()、substring()、substr()用法

  作者: 今日评论: [字体: ]

JavaScript中substr和substring的区别:

String.substr(N1,N2) 从指定的位置(N1)截取指定长度(N2)的字符串;
String.substring(N1,N2) 从指定的位置(N1)到指定的位置(N2)的字符串;

举个例子:
alert("123456789".substr(2,5)) 它显示的是 "34567"
alert("123456789".substring(2,5)) 则显示的为 "345"

JavaScript中String 对象的slice()、substring()、substr()方法都能提取字符串的一部分,但使用时有所区别。

  • stringObject.slice(startIndex,endIndex)

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

1)参数 endIndex 可选,如果没有指定,则默认为字符串的长度 stringObject.length 。【注1】字符串中第一个字符的位置是从【0】开始的,最后一个字符的位置为【stringObject.length-1】,所以slice()方法返回的字符串不包括endIndex位置的字符。

  var stringObject = "hello world!";
   alert(stringObject.slice(
3)); // lo world!

   alert(stringObject.slice(3,stringObject.length)); // lo world!

2)startIndex 、endIndex 可以是负数。如果为负,则表示从字符串尾部开始算起。即-1表示字符串最后一个字符。 【注2】合理运用负数可以简化代码

  var stringObject = "hello world!";
   alert(stringObject.slice(
-3)); // ld!

   alert(stringObject.slice(-3,stringObject.length)); // ld!
   alert(stringObject.slice(-3,-1)); // ld

3)startIndex、endIndex 都是可选的,如果都不填则返回字符串 stringObject 的全部,等同于slice(0) 【注3】String.slice() 与 Array.slice() 相似

  var stringObject = "hello world!";
   alert(stringObject.slice());
// hello world!

   alert(stringObject.slice(0)); // hello world!

4)如果startIndex、endIndex 相等,则返回空串

  • stringObject.substring(startIndex、endIndex)

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

1)startIndex 是一个非负的整数,必须填写。endIndex 是一个非负整数,可选。如果没有,则默认为字符串的长度stringObject.length 。

  var stringObject = "hello world!";
   alert(stringObject.substring(
3)); // lo world!

   alert(stringObject.substring(3,stringObject.length)); // lo world!
   alert(stringObject.substring(3,7)); // lo w,空格也算在内[l][o][ ][w]

2)如果startIndex、endIndex 相等,则返回空串。如果startIndex 比 endIndex 大,则提取子串之前,调换两个参数。即stringObject.substring(startIndex,endIndex)等同于stringObject.substring(endIndex,startIndex) 【注4】substring()相比,slice()更灵活,可以接收负参数。

  var stringObject = "hello world!";
   alert(stringObject.substring(
3,3)); // 空串

   alert(stringObject.substring(3,7)); // lo w
   alert(stringObject.substring(7,3)); // lo w

  • stringObject.substr(startIndex,length)

返回字符串 stringObject 从 startIndex 开始(包括 startIndex )指定数目(length)的字符字符。

1)startIndex 必须填写,可以是负数。如果为负,则表示从字符串尾部开始算起。即-1表示字符串最后一个字符。

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

  var stringObject = "hello world!";
   alert(stringObject.substr(
3)); // lo world!

   alert(stringObject.substr(3,stringObject.length)); // lo world!
   alert(stringObject.substr(3,4)); // lo w

3)substr()可以代替slice()和substring()来使用,从上面代码看出 stringObject.substr(3,4) 等同于stringObject.substring(3,7)

【注5】ECMAscript 没有对该方法进行标准化,因此尽量少使用该方法。

来源:http://hi.baidu.com/%BB%C6%BD%F0vip/blog/item/8563cf94d91ab819d31b7058.html
录入日期:[2010-3-31 10:09:00]
收藏 推荐 打印 | 录入:mikebai | 阅读:
文章评论      
正在加载评论列表...
评论表单加载中...