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

一、字符串的解构赋值 1.1 字符串和数组类似,可以一一对应赋值。 let str = 'abcd'; let [a,b,c,d] = str; // a='a' b='b' c='c' d='d'...

一、字符串的解构赋值

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'

ES5字符串方法

  • 发表于 2020-05-05 23:27
  • 阅读 ( 156 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除