一、对于substring()
substring(start,stop)示意返回从start开始到stop处之间的新字符串,其长度为stop减 start。蕴含start,但不蕴含stop,且不批改原字符串。这一点与slice的含头不含尾相近。例如:
var str = "0123456789";console.log(str.substring(2,6))//"2345"console.log(str.substring(0,9),str)//"012345678" "0123456789"
其中start是必填项,stop为选填项,如果stop不填 那么将返回是start到字符串结尾。例如:
var str = "0123456789";console.log(str.substring(2))//"23456789"
二、对于substr()
substr(start,length)示意返回从start开始蕴含length长度的新字符串,蕴含start,且不批改原字符串,与substring相比,第二个参数由代表完结的下标stop变成了规定新字符串长度的length,例如:
var str = "0123456789";console.log(str.substr(2,6))//"234567"
其中start是必填项,length为选填项,如果length不填 那么将返回是start到字符串结尾。例如:
var str = "0123456789";console.log(str.substr(2))//"23456789"
三、对于slice()
首先要说的是,slice可操作数组和字符串,但substring和substr只能操作字符串,splice只能操作数组。
slice(start,stop)示意截取从下标start 到下标stop(不包含该元素)的之间的元素,并返回新数组/新字符串,并不批改原数组/原字符串,这点下面说了,与substring很类似。例如:
var str = "0123456789"; arr = [0,1,2,3,4,5,6,7,8,9];console.log(str.slice(2,6))//"2345"console.log(arr.slice(2,6))//[2,3,4,5]
四、对于splice()
splice(start,length,items)示意从下标start处截取length长度(与substr有点像)的元素后,在start处为原数组增加items,并返回被截取的新数组,splice会间接批改原数组,例如:
var arr = [0,1,2,3,4,5,6,7,8,9];console.log(arr.splice(1,3,2,3,4))//[1,2,3]console.log(arr);//[0,2,3,4,4,5,6,7,8,9] 原数组被截取走了1,2,3,并退出了2,3,4
当咱们须要在数组中增加元素 length只需改为0或者正数,列如:
var arr = [0,1,2,3,4,5,6,7,8,9];console.log(arr.splice(1,0,2,3,4))//[]console.log(arr);//[0,2,3,4,1,2,3,4,5,6,7,8,9]