【字符串的扩展】

模板字符串

认识模板字符串

  • 普通字符串:
1
2
'字符串'
"字符串"
  • 模板字符串:
1
`字符串`

模板字符串与一般字符串的区别

  • 对于普通用法没有区别
1
2
3
4
const name1 = 'zjr';
const name2 = `zjr`;
console.log(name1, name2, name1 === name2);
// zjr zjr true
  • 字符串拼接的巨大区别
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const person = {
name: 'zjr',
age: 18,
sex: '男'
};

const info =
'我的名字是:' + person.name +
',性别是:' + person.sex +
',今年:' + person.age + '岁';

console.log(info);

// 我的名字是:zjr,性别是:男,今年:18岁
1
2
3
4
5
6
7
8
9
10
11
const person = {
name: `zjr`,
age: 18,
sex: `男`
};

const info = `我的名字是:${person.name},性别是:${person.sex},今年:${person.age}岁`;

console.log(info);

// 我的名字是:zjr,性别是:male,今年:18岁

模板字符串最大的优势:方便注入!

模板字符串的注意事项

输出多行字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 一般字符串
const info = '第一行\n第二行';
console.log(info);
/*
第一行
第二行
*/


// 模板字符串
const info = `第一行
第二行`; // 注意不能有缩进
console.log(info);
/*
第一行
第二行
*/

模板字符串中,所有的空格、换行或缩进都会被保存在输出中

输出 `` ` 等特殊字符

1
2
3
4
const info = `\``;	// ```
const info = `\\`; // `\`
const info = `""`; // `""`
const info = `''`; // `''`

模板字符串的注入

1
2
3
4
5
6
7
8
9
10
11
12
13
const username = 'alex';
const person = {
age: 18,
sex: `male`
};
const getSex = function (sex) {
return sex === `male` ? '男' : '女';
};

const info = `${username},${person.age + 2},${getSex(person.sex)}`;
console.log(info);

// alex,20,男

模板字符串的 ${} 注入可以兼容几乎所有的值!

模板字符串、字符串、数值、布尔值、表达式、函数……(只要结果是个 “值” 即可)

模板字符串的应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>模板字符串的应用</title>
<style>
body {
padding: 50px 0 0 300px;
font-size: 22px;
}

ul {
padding: 0;
}

p {
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>学生信息表</p>
<ul id="list">
<li style="list-style: none;">信息加载中……</li>
</ul>

<script>
// 数据(此处只是模拟数据,后期是通过 Ajax 从后台获取)
const students = [
{
username: 'Alex',
age: 18,
sex: 'male'
},
{
username: 'ZhangSan',
age: 28,
sex: 'male'
},
{
username: 'LiSi',
age: 20,
sex: 'female'
}
];

const list = document.getElementById('list');

let html = '';

for (let i = 0; i < students.length; i++) {
html += `<li>我的名字是:${students[i].username},${students[i].sex},${students[i].age}</li>`;
}

list.innerHTML = html;
</script>
</body>
</html>

alt=“image-20220315130229559”> style=“zoom:50%;” />

includes(), startsWith(), endsWith()

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

  • includes():返回布尔值,表示是否找到了参数字符串。
  • startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。
1
2
3
4
5
let s = 'Hello world!';

s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true

这三个方法都支持第二个参数,表示开始搜索的位置。

1
2
3
4
5
let s = 'Hello world!';

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

上面代码表示,使用第二个参数n时,endsWith的行为与其他两个方法有所不同。它针对前n个字符,而其他两个方法针对从第n个位置直到字符串结束。

repeat()

repeat方法返回一个新字符串,表示将原字符串重复n次。

1
2
3
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""

参数如果是小数,会被取整。

1
'na'.repeat(2.9) // "nana"

如果repeat的参数是负数或者Infinity,会报错。

1
2
3
4
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError

但是,如果参数是 0 到-1 之间的小数,则等同于 0,这是因为会先进行取整运算。0 到-1 之间的小数,取整以后等于-0repeat视同为 0。

1
'na'.repeat(-0.9) // ""

参数NaN等同于 0。

1
'na'.repeat(NaN) // ""

如果repeat的参数是字符串,则会先转换成数字。

1
2
'na'.repeat('na') // ""
'na'.repeat('3') // "nanana"

padStart(),padEnd()

ES2017 引入了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全。

1
2
3
4
5
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

上面代码中,padStart()padEnd()一共接受两个参数,第一个参数是字符串补全生效的最大长度,第二个参数是用来补全的字符串。

如果原字符串的长度,等于或大于最大长度,则字符串补全不生效,返回原字符串。

1
2
'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'

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

1
2
'abc'.padStart(10, '0123456789')
// '0123456abc'

如果省略第二个参数,默认使用空格补全长度。

1
2
'x'.padStart(4) // '   x'
'x'.padEnd(4) // 'x '

padStart()的常见用途是为数值补全指定位数。下面代码生成 10 位的数值字符串。

1
2
3
'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"

另一个用途是提示字符串格式。

1
2
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

trimStart(),trimEnd()

trimStart()trimEnd()这两个方法,它们的行为与trim()一致,trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。它们返回的都是新字符串,不会修改原始字符串。

1
2
3
4
5
const s = '  abc  ';

s.trim() // "abc"
s.trimStart() // "abc "
s.trimEnd() // " abc"

上面代码中,trimStart()只消除头部的空格,保留尾部的空格。trimEnd()也是类似行为。

除了空格键,这两个方法对字符串头部(或尾部)的 tab 键、换行符等不可见的空白符号也有效。

浏览器还部署了额外的两个方法,trimLeft()trimStart()的别名,trimRight()trimEnd()的别名。

at()

at()方法接受一个整数作为参数,返回参数指定位置的字符,支持负索引(即倒数的位置)。

1
2
3
const str = 'hello';
str.at(1) // "e"
str.at(-1) // "o"

如果参数位置超出了字符串范围,at()返回undefined

对象的扩展 运算符的扩展