【深入浅出ES6】字符串与正则表达式

214 阅读2分钟

字符串新增部分功能

识别子字符串方法

  • includes()
  • startwith()
  • endwith()

三个方法均返回bool值,表示子字符串是否存在,且传入的参数必须为字符串,不能是正则表达式 如果希望找到对应出现的确定位置,则仍需要使用已有的indexOf()、lastIndexOf()方法

repeat()

快速生成重复性字符串,函数中的参数表示重复的次数

console.log("x".repeat(3));         // "xxx"
console.log("hello".repeat(2));     // "hellohello"
console.log("abc".repeat(4));       // "abcabcabcabc"

模板字面量 ``

  • 多行字符串:针对多行字符串的形式概念;
  • 基本的字符串格式化:将字符串部分替换为已存在的变量值的能力;
  • HTML 转义:能转换字符串以便将其安全插入到 HTML 中的能力

若你想在字符串中包含反引号,只需使用反斜杠( \ )转义即可,

let message = `\`Hello\` world!`;
console.log(message); // "`Hello` world!"

在字符串中插入js表达式

let count = 10,
price = 0.25,
message = `${count} items cost ¥${(count * price).toFixed(2)}.`;
console.log(message); // "10 items cost ¥2.50."

模板字符串也是js表达式,因此可以使用嵌套模板字符串

let name = "Nicholas",
    message = `Hello, ${
        `my name is ${ name }`
    }.`;

console.log(message);        // "Hello, my name is Nicholas."

标签模板(模板字面量的增强功能)

使用标签模板提供了对模板字面量再加工的能力

设置一个函数,将函数名放在模板字面量前面,作为模板的标签,该标签函数接收到模板字面量中设置的参数,传递到标签函数中

function tag(literals, ...arg){
    console.log(literals) // ["", "my age is ,and your name is ", ""]
    console.log(arg) // [22, "tom"]
    return 'from tag function'
   }

    let age = 22;
    let name = 'tom'
    let result = tag`${ age }my age is ,and your name is ${name}`

   console.log(result)

tag为标签函数

  • 第一个参数literals为数组,元素为模板字面量中被变量分割开的每一个字符串 ["", "my age is ,and your name is ", ""]
  • 第一个参数之后的参数,为模板字面量中依次使用的变量,一般常用 结构符号... 将其放入一个数组中 [22, "tom"]
  • 标签函数中的返回作为标签模板最终的返回值

正则表达式新增部分功能

复制正则表达式 new RegExp()

支持传入第二个参数,表示正则表达式的标志(i:忽略大小写、g:全局匹配),第二个参数会覆盖原有正则中的标志

var re1 = /ab/i,

    // throws an error in ES5, okay in ES6
    re2 = new RegExp(re1, "g");

console.log(re1.toString());            // "/ab/i"
console.log(re2.toString());            // "/ab/g"

console.log(re1.test("ab"));            // true
console.log(re2.test("ab"));            // true

console.log(re1.test("AB"));            // true
console.log(re2.test("AB"));            // false

获取正则表达式标志位flags属性

var re = /ab/g;
console.log(re.source); // "ab"
console.log(re.flags); // "g"