提取字符串/数组中元素的方法

来源:互联网 发布:申通淘宝面单打印软件 编辑:程序博客网 时间:2024/05/22 04:19

字符串

1.substr()方法

语法:string.substr(start,length)

功能:指定提取字符串中字符开始的位置(start下标)以及字符长度(length)

备注:start可以是正数(字符串从左往右数的下标)也可以是负数(从右往左数的下标),-1 指字符串中最后一个字符,-2 指倒数第二个字符;

   如果不备注length那么默认到字符串结尾的位置。


2.substring()方法

语法:string.substring(from,to)

功能:指定提取字符串中字符开始的位置(from)以及结束的位置(to)

备注:start只能是正数

   如果不备注to那么默认到字符串结尾的位置


数组/字符串

1.slice()方法

语法:array.slice(start,end) 

   str.slice(start,end)

功能:指定提取数组中开始的位置(start)以及结束的位置(end)

备注:start可以为正数可以为负数

如果不备注end则默认到数组结尾的位置


eg:
<script>var str="Hello world!";var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];document.write(str.substring(3)+"<br>");document.write(str.substring(3,7)+"<br>");document.write(str.substr(3)+"<br>");document.write(str.substr(3,7)+"<br>");document.write(str.slice(3)+"<br>");document.write(str.slice(3,7)+"<br>");document.write( fruits.slice(1)+"<br>");document.write( fruits.slice(1,3)+"<br>");</script>

运行结果:
lo world!lo wlo world!lo worllo world!lo wOrange,Lemon,Apple,MangoOrange,Lemon


原创粉丝点击