<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6字符串新增特性</title>
</head>
<body>
<script>
//判断字符串中是否包含某个字符
{
let str = 'string';
console.log(str.includes('r'));//true
console.log(str.includes('c'));//false
}
//判断字符串是否以某些字符起始
//判断字符串是否以某些字符结束
{
let str = 'string';
console.log(str.startsWith('str'));//true
console.log(str.endsWith('ng'));//true
}
//重复
{
let str = 'abc';
console.log(str.repeat(3));//abcabcabc
}
//模版字符串
{
let info = 'world';
let m = `hello ${ info }`
console.log(m);//hello world
}
//补白
//可应用于日期中
{
console.log('1'.padStart(2, '0'));//01
console.log('1'.padEnd(2, '0'));//10
}
//标签模版
//可用于过滤html字符串,防止xss攻击
//可用于处理多国语言转换
{
let user = {
name: 'list',
info: 'hello world'
}
function abc(s, v1, v2) {
console.log(s, v1, v2);
return s+v1+v2;
}
abc`i am ${ user.name }, ${ user.info }`
console.log(abc`i am ${ user.name }, ${ user.info }`);
}
//raw保证转义\不生效
{
console.log(String.raw`hi\nworld`);//hi\nworld
console.log(`hi\nworld`);
//hi
//world
}
</script>
</body>
</html>