美文网首页
slice,substr和substring的区别

slice,substr和substring的区别

作者: Allan要做活神仙 | 来源:发表于2017-03-14 17:40 被阅读45次

    slice,substring,substr三个函数都是截取字符串,但是对参数的处理有区别

    参数处理相似的两个函数式slice和substring

    slice(start,end)和substring(start,end)

    他们两个的end都是原字符串的索引,意思为截取到end(不包括end)位置的字符

    二者的区别是:
    slice中的start如果为负数,会从尾部算起,-1表示倒数第一个,-2表示倒数第2个,此时end必须为负数,并且是大于start的负数,否则返回空字符串

    slice的end如果为负数,同样从尾部算起,如果其绝对值超过原字符串长度或者为0,返回空字符串

    substring会取start和end中较小的值为start,二者相等返回空字符串,任何一个参数为负数被替换为0(即该值会成为start参数)

    slice和substring:
    都接收两个参数,接收的是起始位置和结束位置(不包括结束位置)

    substr
    接收的则是起始位置和所要返回的字符串长度。直接看下面例子:

           var test = 'hello world';
     
           alert(test.slice(4,7));             //o w
           alert(test.substring(4,7));  等同于 alert(test.substring(7,4));        //o w
            alert(test.substr(4,7));            //o world
    

    相关文章

      网友评论

          本文标题:slice,substr和substring的区别

          本文链接:https://www.haomeiwen.com/subject/vlwhnttx.html