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
  • 相关阅读:
    Delphi XE4 FireMonkey 开发 IOS APP 发布到 AppStore 最后一步.
    Native iOS Control Delphi XE4
    Delphi XE4 iAD Framework 支持.
    using IOS API with Delphi XE4
    GoF23种设计模式之行为型模式之命令模式
    Android青翼蝠王之ContentProvider
    Android白眉鹰王之BroadcastReceiver
    Android倚天剑之Notification之亮剑IOS
    Android紫衫龙王之Activity
    GoF23种设计模式之行为型模式之访问者模式
  • 原文地址:https://www.cnblogs.com/xlj-code/p/10348671.html
Copyright © 2011-2022 走看看