mikebai.com

  • Home
  • dev
  • DotNET
  • M365
  • 搞笑
  • 杂七杂八
  • FocusDict
個人BLOG
it developer
  1. Main page
  2. DotNET
  3. Main content

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

2010-03-31 146hotness 0likes 0comments






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));
Tag: Nothing
Last updated:2010-03-31

mikebai

This person is a lazy dog and has left nothing

Like
< Last article
Next article >

COPYRIGHT © 2025 mikebai.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang