ES6之字符串扩展

2018-01-15  本文已影响0人  hawkzz

作者原文:http://hawkzz.com/blog/blog/1516005005651

字符串遍历器

字符串可以被for..of循环遍历。

let str = 'hello';
for(let key of str){
    console.log(key);
}

输出:
//h
//e
//l
//l
//o

字符串模板

ES6添加字符串模板,让js能够更加方便的拼接字符串和变量;下面来做个比较:

//ES5

let firstName = 'Jon';
let lastName = 'Smith';
let html = 'My firstName is:' + firstName + 
    ',my lastName is:'+ lastName;
console.log(html);

//ES6

let html = `My firstName is:${firstName},my lastName is:${lastName}`;

从上面两端代码看出,ES6明显在写法上简单,好理解;模板字符串用反引号标识,它可以当普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量;也拥有计算功能;

let x  = 1;
let y = 2;

let str = `${x} + ${y} = ${x + y}`;
console.log(str);

//输出
1 + 2 = 3;

查询方法

以前,js只能通过indexOf方法返回值是否大于0,判断一个字符串是否包含在另一个字符串中;ES6扩展了几个方法:

let str = 'Hello World!';
console.log(str.includes('o'));//true
console.log(str.startsWith('Hello'));//true
console.log(str.endsWith('!'));//true

还可以传第二个参数,表示从什么位置开始搜索;

let str = 'Hello World!';

console.log(str.includes('Hello',2));//false
console.log(str.startsWith('World',6));//true
console.log(str.endsWith('Hello',5));//true

repeat()

ES6新增了一个repeat方法,用来将原字符串重复n次;规则:

console.log('x'.repeat(3));//xxx
console.log('xxx'.repeat(0));//""
console.log('x'.repeat(2.8));//xx
console.log('x'.repeat(2.1));//xx
// console.log('x'.repeat(Infinity));//Error
// console.log('x'.repeat(-2));//Error
console.log('x'.repeat(-0.2));//""
console.log('x'.repeat(NaN));//""
console.log('x'.repeat('3'));//xxx

补全长度功能

如果某个字符串不够指定长度,会在头部或者尾部补全;

这两个方法有两个参数,第一个为字符串的总长度len,第二个为用了补全的字符串str;规则:

let str = 'abc';

console.log(str.padStart(2,'123'));//'abc';
console.log(str.padEnd(2,'123'));//'abc'

console.log(str.padStart(10,'1234567890'));//1234567abc
console.log(str.padEnd(10,'1234567890'));//abc1234567

console.log(str.padStart(10,'123'));//1231231abc
console.log(str.padEnd(10,'123'));//abc1231231

console.log(str.padStart(4));//' abc'
console.log(str.padEnd(4));//'abc '
上一篇 下一篇

猜你喜欢

热点阅读