ES6中的字符串(模板字符串、字符串新方法)

摘要:字符串和数组类似,可以一一对应赋值。字符串有length属性,可以对它解构赋值。使用反引号(``)代替普通的单引号或双引号。使用${expression}作为占位符,可以传入变量。

一、字符串的解构赋值

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

二、模板字符串

使用反引号(``)代替普通的单引号或双引号。
使用${expression}作为占位符,可以传入变量。
let str = '世界';
let newStr = `你好${str}!`; // '你好世界!'
支持换行。
let str = `
      条条大路通罗马。
      条条大路通罗马。
      条条大路通罗马。
`;

三、字符串新方法

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()

判断当前字符串是否给定字符串开头 / 结尾,返回布尔值。
let str = 'hello world';
console.log(str.startsWith('hello'));
console.log(str.endsWith('world'));

用途:检测地址、检测上传的文件是否以xxx结尾。

3.3 String.prototype.repeat(次数)

以指定的次数复制当前字符串,并返回一个新的字符串。
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()

填充字符串。可以输入两个参数,第一个参数是前后填充的字符总数,第二个参数是用来填充的字符串。
let str = 'hello';
console.log(str.padStrat(10,'world')); // 'helloworld'
let pad = 'mmgg';
console.log(str.padEnd(str.length+pad.length, pad)); // 'mmgghello'

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_8888