zoukankan      html  css  js  c++  java
  • ES6中字符串的扩展

    一、查找字符串

    在ES5中,可以使用 indexOf 方法和 lastIndexOf 方法查找字符串:

    let str = 'hello world';
    alert(str.indexOf('o'));   // 4
    alert(str.lastIndexOf('o'));   // 7
    alert(str.lastIndexOf('z'));   // -1

     ES6中,又新增了3个方法用于特定字符的查找。

    1、includes()

    该方法传入一个字符串参数,然后返回一个布尔值,表示是否在指定字符串中找到了该字符串片段。

    let str = 'hello';
    console.log(str.includes('h'));   // true
    console.log(str.includes('z'));   // false

    2、startsWith()

    该方法传入一个字符串参数,然后返回一个布尔值,表示是否在指定字符串开头找到了该字符串片段。

    let str = 'hello';
    console.log(str.startsWith('h'));   // true
    console.log(str.startsWith('lo'));   // false

    3、endsWith()

    该方法传入一个字符串参数,然后返回一个布尔值,表示是否在指定字符串末尾找到了该字符串片段。

    let str = 'hello';
    console.log(str.endsWith('h'));   // false
    console.log(str.endsWith('o'));   // true

     

    二、操作字符串

    1、repeat()

    对一个字符串进行重复,返回一个新字符串。

    let str = 'ha';
    console.log(str.repeat(3));   'hahaha'

    参数如果是小数,会被向下取整进行操作。

    let str = 'ha';
    console.log(str.repeat(2.9));   'haha'

    参数如果是负数,会报错。

    let str = 'ha';
    console.log(str.repeat(-2));   // error

     

    三、模板字符串

    ES6引入了模板字符串,用反引号标识( ` ),主要功能有俩个。

    1、定义多行字符串。

    let str = `hello
    hello
    hello`;
    console.log(str)
    // hello
    // hello
    // hello

    2、在字符中嵌入变量,把变量包裹在 ${} 中即可。

    var username = 'tom';
    alert(`hello ${username}`);   // hello tom
  • 相关阅读:
    UVaLive 7362 Farey (数学,欧拉函数)
    UVaLive 7361 Immortal Porpoises (矩阵快速幂)
    UVaLive 7359 Sum Kind Of Problem (数学,水题)
    CodeForces 706D Vasiliy's Multiset (字典树查询+贪心)
    负载均衡服务器
    集群-如何理解集群?
    架构规划
    领域模型
    状态图
    E-R图
  • 原文地址:https://www.cnblogs.com/xlj-code/p/10348671.html
Copyright © 2011-2022 走看看