zoukankan      html  css  js  c++  java
  • ES6小实验-字符串的扩展

    ES6里面的对字符串的扩展实际上就是增加了一些方法,使对字符串的操作更加完善,下面做几个小实验来验证下:

      includes(): 返回布尔值,表示是否找到了参数字符串,支持第二的参数,表示开始的位置

    'use strict';
    
    var s = 'Hello world!';
    console.log(s.includes('Hello'));//true

      startsWith(): 返回布尔值,表示参数字符串是否在源字符串的头部,支持第二的参数,表示开始的位置

    'use strict';
    
    var s = 'Hello world!';
    console.log(s.startsWith('Hello'));//true

      endsWith(): 返回布尔值,表示参数字符串是否在源字符串的尾部,支持第二的参数,表示开始的位置

    'use strict';
    
    var s = 'Hello world!';
    console.log(s.endsWith('Hello'));//false

      repeat(): 表示将原字符串重复n次

    'use strict';
    
    var s = 'Hello world!';
    console.log(s.repeat(3));//Hello world!Hello world!Hello world!

      ES7推出了字符串长度补全功能,padStart(),padEnd(),它们接收两个参数,第一个用来指定字符串的最小长度,第二个用来补全字符串

    'use strict';
    
    var s = 'x';
    console.log(s.padStart(5, 'ab'));//ababx
    console.log(s.padEnd(4, 'ab'));//xaba

      如果用来补全的字符串与原字符串,两者的长度之和超过了指定的最小长度,则会截去超出位数的补全字符串

    'use strict';
    
    var s = '09-12';
    console.log(s.padStart(10, 'YYYY-MM-DD'));//YYYY-09-12

    模板字符串

      模板字符串中嵌入变量,需要将变量名写在 ${}  之中

    'use strict';
    
    var name = "bob"
    var time = "today"
    
    console.log(`hello ${name},how are you ${time}`)//hello bob,how are you today
  • 相关阅读:
    LeetCode Find Duplicate File in System
    LeetCode 681. Next Closest Time
    LeetCode 678. Valid Parenthesis String
    LeetCode 616. Add Bold Tag in String
    LeetCode 639. Decode Ways II
    LeetCode 536. Construct Binary Tree from String
    LeetCode 539. Minimum Time Difference
    LeetCode 635. Design Log Storage System
    LeetCode Split Concatenated Strings
    LeetCode 696. Count Binary Substrings
  • 原文地址:https://www.cnblogs.com/fengz/p/6661316.html
Copyright © 2011-2022 走看看