zoukankan      html  css  js  c++  java
  • es6基础系列四--字符串的拓展

    1 for...of 字符串的遍历接口

    for(let i of "abc"){
    	console.log(i);
    }
    // a
    // b
    // c
    

    2 includes 是否包含某字符串,返回布尔值

    格式:str.includes(searchString[, position])
    与indexOf的对比:
    indexOf:返回下标,判断是否包含某字符串,下标是字符串的位置
    includes:返回布尔值,是否包含某字符串,如果只是判断字符串中包含,此法可行。

    var s = "hello";
    // es5
    s.indexOf("o"); // 4
    // es6
    s.includes("o"); // true
    s.includes("d"); // false
    s.includes("h", 2); // false 从第三个字符开始找
    

    3 startsWith 参数字符串是否在源字符串的头部,返回布尔值

    格式:str.startsWith(searchString[, position])

    var s = "hello world";
    // es5
    s.indexOf("hello"); // 0 等于0表示就在源字符串头部
    // es6
    s.startsWith("hello"); // true
    s.startsWith("world"); // false
    s.startsWith("world", 6); // true
    

    4 endsWith 跟startsWith相反,表示参数字符串是否在源字符串的尾部,返回布尔值

    格式:str.endsWith(searchString[, position])

    var s = "hello world";
    // es5
    String.prototype.endWith=function(endStr){
      var d=this.length-endStr.length;
      return (d>=0&&this.lastIndexOf(endStr)==d)
    }
    s.endWith("world"); // true
    // es6
    s.endsWith("world"); // true
    s.endsWith("world", 5); // false
    s.endsWith("hello", 5); // true
    

    5 repeat 将原字符串重复n次,返回一个新字符串

    var s = "s";
    s.repeat(3); // sss
    s.repeat(2.6); // ss 小数会被取整
    s.repeat(-2); // RangeError 报错
    s.repeat(0); // ""
    

    6 模板字符串 是增强版的字符串,用反引号(`)标识。

    它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量,好处相当明显,不用再拼接字符串,使用模板字符串内部可以使用变量了。

    // es5 输出模板通常是如下格式,相当繁琐还不方便
    var name="Bob",time="today";
    var resultStr = "hello "+name+", how are you "+time+'?'; //hello Bob, how are you today?
    // es6 模板字符串
    console.log(`string text line 1
    string text line 2`);
    //string text line 1
    //string text line 2
    
    // 直接用${变量名}表示
    `Hello ${name}, how are you ${time}?` // Hello Bob, how are you today?
    // 使用表达式
    var obj={a:1,b:2};
    `${obj.a+obj.b}` // 3
    // 使用函数
    function fn() {
      return "Hello World";
    }
    `this is fn return str: ${fn()}` // this is fn return str: Hello World
    

    具体es6关于字符串的变化、拓展请查看MDN官网

  • 相关阅读:
    UISearchBar clearButton
    github上不了改下host
    github命令
    quick-lua调试
    UIButton Making the hit area larger
    linux中crontab实现以秒执行任务
    学习linux必备服务器VPS
    JAVA线程全局异常处理
    spring基础
    <s:select>自动加标签
  • 原文地址:https://www.cnblogs.com/yanyuji/p/6813874.html
Copyright © 2011-2022 走看看