关于JS 中的 substring() ;substr();slice();,他们都可以截取选定的元素;
其中,substring(),substr()方法只适用于字符串,不能作用于数组;
substring()定义:
substring() 方法用于提取字符串中介于两个指定下标之间的字符。
语法:
stringObject.substring(starPos,stopPos)
参数说明:
注意:
1. 返回的内容是从 start开始(包含start位置的字符)到 stop-1 处的所有字符,其长度为 stop 减start。
2. 如果参数 start 与 stop 相等,那么该方法返回的就是一个空串(即长度为 0 的字符串)。
3. 如果 start 比 stop 大,那么该方法在提取子串之前会先交换这两个参数。
substr() 方法从字符串中提取从 startPos位置开始的指定数目的字符串。
语法:
stringObject.substr(startPos,length)
参数说明:
注意:如果参数startPos是负数,从字符串的尾部开始算起的位置。也就是说,-1 指字符串中最后一个字符,-2 指倒数第二个字符,以此类推。
如果startPos为负数且绝对值大于字符串长度,startPos为0。
选定元素slice()
其中,substring(),substr()方法只适用于字符串,不能作用于数组;
而slice(),方法可以作用于数组中.
eg:
eg:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Array对象 </title>
<script type="text/javascript">
var myarr = new Array("一","二","三","四","五","六");
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Array对象 </title>
<script type="text/javascript">
var myarr = new Array("一","二","三","四","五","六");
var myarrs = myarr.join("")
document.write(myarr + "<br>");
document.write("myarrd的类型"+typeof(myarr)+"</br>")
document.write(myarr.slice(2,4) + "<br>");
document.write("myarr.slice的类型"+typeof(myarr.slice(2,4))+"</br>")
document.write(myarr+"</br>");
document.write("myarrd的类型"+typeof(myarr)+"</br>";
document.write(myarr + "<br>");
document.write("myarrd的类型"+typeof(myarr)+"</br>")
document.write(myarr.slice(2,4) + "<br>");
document.write("myarr.slice的类型"+typeof(myarr.slice(2,4))+"</br>")
document.write(myarr+"</br>");
document.write("myarrd的类型"+typeof(myarr)+"</br>";
document.write(myarrs.substring(2,4)+"</br>")
document.write("myarrs:___"+typeof(myarrs)+"</br>");
document.write(myarrs.slice()+"</br>")
document.write(typeof(myarrs.slice()));
</script>
</head>
<body>
</body>
</html>
document.write("myarrs:___"+typeof(myarrs)+"</br>");
document.write(myarrs.slice()+"</br>")
document.write(typeof(myarrs.slice()));
</script>
</head>
<body>
</body>
</html>
输出的结果:
一,二,三,四,五,六
myarrd的类型object
三,四
myarr.slice的类型object
一,二,三,四,五,六
myarrd的类型object
三四
myarrs:___string
一二三四五六
string
myarrd的类型object
三,四
myarr.slice的类型object
一,二,三,四,五,六
myarrd的类型object
三四
myarrs:___string
一二三四五六
string