字符串中substring(),substr(),slice()方法用法

来源:互联网 发布:少年三国志五星刀数据 编辑:程序博客网 时间:2024/05/20 12:21

根据w3c

1.substring():从 start 处到 stop-1 处的所有字符,其长度为 stop 减start,不接受负的参数stringObject.substring(start,stop)

<script type="text/javascript">

var str="hello world!"

alert(str.substring( ));//hello world!

alert(str.substring(1));//ello world!

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

alert(str.substring(-7)); //hello world!,虽说不接受负数,但也不出错,相当于str.substring(0)

alert(str.substring(-5,-4)); //空字符

alert(str.substring(3,1)); //参数相当于(1,3),输出el

</script>

2.substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符,不建议使用,stringObject.substr(start,length)

alert(str.substr( ));//hello world!
alert(str.substr(1));//ello world!
alert(str.substr(3,7)); //lo worl
alert(str.substr(-7)); //hello world!
alert(str.substr(3,1)); //l


3.slice() 方法可提取字符串的某个部分,并以新的字符串返回被提取的部分,如果是负数,则该参数规定的是从字符串的尾部开始算起的位置,该方法较灵活stringObject.slice(start,end)

alert(str.slice( ));//hello world!
alert(str.slice(1));//ello world!
alert(str.slice(3,7)); //lo w,以上三个例子,根substring用法类似
alert(str.slice(-5)); //orld!
alert(str.slice(-5,-4)); //o ,两者都为负无法取到最后一个字符
alert(str.slice(3,1)); //