A
、字符串模板的应用
---
连接
模板字符串(
template string
)是
增强版的字符串
,用
反引号(
`
)
标识。它可以当作普通字符串使用,也可以
用来定义多行字符串,或者在字符串中嵌入变量。
// 普通字符串
`In JavaScript '\n' is a line-feed.`
// 多行字符串
`In JavaScript this is
not legal.`
console.log(`string text line 1
string text line 2`);
// 字符串中嵌入变量
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
ES5
中的用法
:
let name ='Strive';
let age = 18;
let str = '
这个人叫
'+name+',
年龄是
'+age+'
岁
';
ES6
中的作法
` ${
变量名字
}`
let str = `
这个人叫
${name},
年龄是
${age}
岁
`;
//
字符串模板
又如:
ES5
$('#result').append('There are <b>' + basket.count + '</b> ' +
' items in your basket, ' +'<em>' + basket.onSale + '</em> are on sale!');
ES6
$('#result').append(`There are <b>${basket.count}</b> items in your basket,
<em>${basket.onSale}
</em>are on sale!`);
说明:
1.
如果在模板字符串中需要使用反引号,则前面要用
反斜杠
转义。
例如: let greeting = `\`Yo\` World!`;
2.
如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中
$('#list').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`);
去 掉空格
$('#list').html(` <ul> <li>first</li> <li>second</li> </ul> `.trim());
3.
模板字符串中嵌入变量,需要将变量名写在
${}
之中。
function authorize(user, action) {
if (!user.hasPrivilege(action)) {
throw new Error(
// 传统写法为
// 'User '
// + user.name
// + ' is not authorized to do '
// + action
// + '.'
`User ${user.name} is not authorized to do ${action}.`);
}
}
4.
大括号内部可放入任意的
JavaScript
表达式,可以进行运算,以及引用对象属性。
let x = 1;
let y = 2;
`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"
`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"
let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"
5.
模板字符串之中还能调用函数。
function fn() { return "Hello World"; } `foo ${fn()} bar`
// foo Hello World bar
//
如果大括号中的值不是字符串,将按照一般的规则转为字符串。
//
比如,大括号中是一个对象,将默认调用对象的
toString
方法。
如果模板字符串中的变量没有声明,将报错。
// 变量 place 没有声明
let msg = `Hello, ${place}`;
// 报错
6.
如果大括号内部是一个字符串,将会原样输出。
`Hello ${'World'}`
// "Hello World
7.
模板字符串可以嵌套
const tmpl = addrs => `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}</td></tr>
<tr><td>${addr.last}</td></tr>
`).join('')}
</table>
`;
8.
如果需要引用模板字符串本身,在需要时执行,可以写成函数
let func = (name) => `Hello ${name}!`;
func('Jack') // "Hello Jack!"
//模板字符串写成了一个函数的返回值。执行这个函数,就相当于执行这个模板字符串了。
◆
常见应用
:
读取后台
json
数据
B.字符串模板新增的方法
1
在
ES5
中确定一个字符是否被另一字符包围的方法
stringObject.
indexOf
(
searchvalue
,fromindex)indexOf()
如
:
var str="Hello world!"
document.write(str.
indexOf
("Hello") + "<br />");
document.write(str.
indexOf
("World") + "<br />");
document.write(str.
indexOf
("world"));
相关方法
: charCodeAt()
方法、
lastIndexOf()
方法、
substring()
方法
2
、判断浏览器
includes
方法
includes()
:返回布尔值,表示是否找到了参数字符串。
if(navigator.userAgent.includes('Chrome'))
3
、
ES6
中与字符串查找相关的其它方法
startsWith()
:
返回布尔值,表示参数字符串是否在原字符串的头部。
endsWith()
:
返回布尔值,表示参数字符串是否在原字符串的尾部
。
let s = 'Hello world!';
s.startsWith('Hello')
// true
s.endsWith('!')
// true
s.includes('o')
// true
这三个方法都支持第二个参数,表示开始搜索的位置。
let s = 'Hello world!';
s.startsWith('world', 6)
// true
s.endsWith('Hello', 5)
// true
s.includes('Hello', 6)
// fal
使用第二个参数
n
时,
endsWith
的行为与其他两个方法有所不同。它针对前
n
个字符,
而其他两个方法针对从第
n
个位置直到字符串结束
Repeat
repeat
方法返回一个新字符串,表示将原字符串重复
n
次
'x'.repeat(3)
// "xxx"
'hello'.repeat(2)
// "hellohello"
'na'.repeat(0) // ""
padStart
、
padEnd
padStart()
用于头部补全,
padEnd()
用于尾部补全。
'x'.padStart(5, 'ab')
// 'ababx'
'x'.padStart(4, 'ab')
// 'abax'
'x'.padEnd(5, 'ab')
// 'xabab'
'x'.padEnd(4, 'ab')
// 'xaba'
trimStart()、trimEnd()
trimStart()
和
trimEnd()
这两个方法。它们的行为与
trim()
一致,
trimStart()
消除字符串头部的空格,
trimEnd()
消除尾部的空格。它们返回的都是新字符串,不会修改原始字符串。
const s = ' abc ';
s.trim()
// "abc" 全 部删除
s.trimStart()
// "abc " 左删除
s.trimEnd()
// " abc" 右删除