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

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'

ES5字符串方法

相關文章
相關標籤/搜索