ES6学习之路

82 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情

模板字面量template string

模板字符串(template string)是增强版的字符串,用反引号标识。

它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。如果在模板字符串中需要使用反引号,则前面要用反斜杠转义

// 字符串中嵌入变量
let name = "pig", time = "today";
`Hello my name is ${name}.`

// 转义
let tatto = `\`Yoyo\` welcome to my new World!`;
tatto; // `Yoyo` welcome to my new World!

标签模板

标签模板其实不是模板,而是函数调用的一种特殊形式。标签指的就是函数,紧跟在后面的模板字符串就是它的参数

alert`hello`
// 等同于
alert(['hello'])

但是,如果模板字符里面有变量,就不是简单的调用了,而是会将模板字符串先处理成多个参数,再调用函数。

function tag(s, v1, v2) {
  console.log(s[0]);
  console.log(s[1]);
  console.log(s[2]);
  console.log(v1);
  console.log(v2);

  return "OK";
}

let a = 5;
let b = 10;
tag`Hello ${ a + b } world ${ a * b }`;
// 输出
'Hello' 
' world' 
''
15
50
'OK'

标签模板还可以过滤 HTML 字符串,防止用户输入恶意内容。

字符串新增方法

原来JavaScript只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。ES6 又提供了三种新方法。

  • includes() :返回布尔值,表示是否找到了参数字符串。
  • startsWith() :返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith() :返回布尔值,表示参数字符串是否在原字符串的尾部。

这三个方法都接收两个参数: 第一个参数是我们要查找的字符(串),第二个参数是数字n,即我们要从第n个位置开始查找。

注意:endsWith不一样,它查找的范围是(0,n-1)

const s = 'hello world'
s.startsWith('he') // true
s.startsWith('he',4) // false
s.endsWith('ld') // true
s.endsWith('ld',4) // false
s.endsWith('ld',11) // true
s.includes(' ') // true

repeat():返回一个新字符串,表示将原字符串重复n次。

'nuna '.repeat(5) // 'nuna nuna nuna nuna nuna '

matchAll():方法返回一个正则表达式在当前字符串的所有匹配。写法:str.matchAll(regexp) 注意点: regexp里一定要写明/g,否则会报错

const str = 'ReguralExpresion RegExr'
const reg = /E(x)([a-z])/
const match = str.matchAll(reg) // TypeError: String.prototype.matchAll called with a non-global RegExp argument

const reg1 = /E(x)([a-z])/g
const match1 = str.matchAll(reg1)
Array.from(match1, (res) => console.log(res));
//Array ["Exp", "x", "p"]
//Array ["Exr", "x", "r"]

replaceAll():方法,可以一次性替换所有匹配。

const str = 'nuna heart nuna heart heart'
str.replaceAll('heart','❤') // 'nuna ❤ nuna ❤ ❤'