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


一、字符串的解構賦值

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字符串方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM