zoukankan      html  css  js  c++  java
  • ES6中的字符串(模板字符串、字符串新方法)

    一、字符串的解构赋值

    1.1 字符串和数组类似,可以一一对应赋值。

    let str = 'abcd';
    let [a,b,c,d] = str; 
    // a='a' b='b' c='c' d='d'                                                                                                         
    

    1.2 字符串有length属性,可以对它解构赋值。

    let {length:len} = str;
    // len=4
    

    二、模板字符串

    使用反引号(``)代替普通的单引号或双引号。
    使用${expression}作为占位符,可以传入变量。

    let str = '世界';
    let newStr = `你好${str}!`; // '你好世界!'
    

    支持换行。

    let str = `
          条条大路通罗马。
          条条大路通罗马。
          条条大路通罗马。
    `;
    

    三、字符串新方法

    3.1 String.prototype.includes(str)

    判断当前字符串中是否包含给定的字符串,返回布尔值。

    let str = 'hello world';
    console.log(str.include('hello')); // true
    

    用途:判断浏览器类型。

    if(navigator.userAgent.includes('Chrome')) {
          alert('这是Chrome浏览器!');
    }else alert('这不是Chrome浏览器!');
    

    3.2 String.prototype.startsWith(xxx) / String.prototype.endsWith()

    判断当前字符串是否给定字符串开头 / 结尾,返回布尔值。

    let str = 'hello world';
    console.log(str.startsWith('hello'));
    console.log(str.endsWith('world'));
    

    用途:检测地址、检测上传的文件是否以xxx结尾。

    3.3 String.prototype.repeat(次数)

    以指定的次数复制当前字符串,并返回一个新的字符串。

    let str = 'mm and gg';
    console.log(str.repeat(3)); // 'mm and ggmm and ggmm and gg'
    

    3.4 String.prototype.padStart(targetLength[,padString]) / String.prototype.padEnd()

    填充字符串。可以输入两个参数,第一个参数是前后填充的字符总数,第二个参数是用来填充的字符串。

    let str = 'hello';
    console.log(str.padStrat(10,'world')); // 'helloworld'
    let pad = 'mmgg';
    console.log(str.padEnd(str.length+pad.length, pad)); // 'mmgghello'
    

    ES5字符串方法

  • 相关阅读:
    ES6-Generator
    ES6-Iterator & for...of循环
    ES6-Proxy and Reflect
    在Main中定义student的结构体,进行年龄从大到小依次排序录入学生信息。(结构体的用法以及冒泡排序)
    函数的调用(取两个整型变量中的最大值)
    将一个字符串数组的元素的顺序进行翻转。。
    枚举类型练习
    利用Arraylist输入学生的成绩,求出平均分和总分。
    简单的推箱子游戏(利用数组)
    枚举类型的声明
  • 原文地址:https://www.cnblogs.com/buildnewhomeland/p/12832053.html
Copyright © 2011-2022 走看看