zoukankan      html  css  js  c++  java
  • slice、substring、substr的区别

    首先,他们一般都接收两个参数,slice和substring接收的是起始位置和结束位置(不包括结束位置),而substr接收的则是起始位置和所要返回的字符串长度。直接看下面例子:

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

    如果只传一个个参数,那么截取这个参数后面的:

     var test = 'hello world';
     alert(test.slice(4));             //o world
     alert(test.substring(4));         //o world
     alert(test.substr(4));            //o world

    这里有个需要注意的地方就是:substring是以两个参数中较小一个作为起始位置,较大的参数作为结束位置。

    如:

    alert(test.substring(7,4));          //o w

    当接收的参数是负数时,slice会将它字符串的长度与对应的负数相加,结果作为参数;substr则仅仅是将第一个参数与字符串长度相加后的结果作为第一个参数;substring则干脆将负参数都直接转换为0。测试代码如下:

    var test = 'hello world';
    
        alert(test.slice(-3));         //rld
        alert(test.substring(-3));     //hello world
        alert(test.substr(-3));        //rld
        alert(test.slice(3,-4));       //lo w
        alert(test.substring(3,-4));   //hel
        alert(test.substr(3,-4));      //空字符串
  • 相关阅读:
    学习笔记
    核心网概要学习
    python基础知识
    python_基础知识_py运算符
    python_基础知识
    将博客搬至CSDN
    poj1182测试数据过了,但A不了,暂时放在这,以后再看
    score——3354
    杭电1241
    杭电1010(WA)
  • 原文地址:https://www.cnblogs.com/leiyangs/p/7967620.html
Copyright © 2011-2022 走看看