1、字符串的解构赋值
1.1 字符串和数组相似,能够一一对应赋值。
let str = 'abcd'; let [a,b,c,d] = str; // a='a' b='b' c='c' d='d'
1.2 字符串有length属性,能够对它解构赋值。
let {length:len} = str; // len=4
2、模板字符串
使用反引号(``)代替普通的单引号或双引号。
使用${expression}
做为占位符,能够传入变量。
html
let str = '世界'; let newStr = `你好${str}!`; // '你好世界!'
支持换行。express
let str = ` 条条大路通罗马。 条条大路通罗马。 条条大路通罗马。 `;
3、字符串新方法
3.1 String.prototype.includes(str)
判断当前字符串中是否包含给定的字符串,返回布尔值。数组
let str = 'hello world'; console.log(str.include('hello')); // true
用途:判断浏览器类型。浏览器
if(navigator.userAgent.includes('Chrome')) { alert('这是Chrome浏览器!'); }else alert('这不是Chrome浏览器!');
3.2 String.prototype.startsWith(xxx) / String.prototype.endsWith()
判断当前字符串是否以给定字符串开头 / 结尾,返回布尔值。ui
let str = 'hello world'; console.log(str.startsWith('hello')); console.log(str.endsWith('world'));
用途:检测地址、检测上传的文件是否以xxx结尾。spa
3.3 String.prototype.repeat(次数)
以指定的次数复制当前字符串,并返回一个新的字符串。prototype
let str = 'mm and gg'; console.log(str.repeat(3)); // 'mm and ggmm and ggmm and gg'
3.4 String.prototype.padStart(targetLength[,padString]) / String.prototype.padEnd()
填充字符串。能够输入两个参数,第一个参数是先后填充的字符总数,第二个参数是用来填充的字符串。code
let str = 'hello'; console.log(str.padStrat(10,'world')); // 'helloworld' let pad = 'mmgg'; console.log(str.padEnd(str.length+pad.length, pad)); // 'mmgghello'