iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 5
0
Modern Web

從ES到ESNext - 30天輕鬆掌握ECMAScript系列 第 5

ES2015(ES6) - string

本系列文章經過重新編排和擴充,已出書為ECMAScript關鍵30天。原始文章因當時準備時程緊迫,多少有些許錯誤。為了避免造成讀者的困擾,以及配合書籍的內容規劃,將會陸續更新本系列文章。
本篇文章在 2021/11/5 已更新。

今天介紹的是關於字串的處理,包括實體方法的擴充,以及對於字串宣告制定新的定義方式。

實體方法

String.prototype.includes(target, position)

檢查 target 是否存在。結果回傳布林值。position 可以指定開始搜尋的索引值。預設值為 0。

const str = "One Punch Man!!";             
const result1 = str.includes('Punch');      //true
const result2 = str.includes('Punch', 3);   //true
const result3 = str.includes('Punch', 5);   //false

String.prototype.startsWith(target, position)

檢查是否以 target 開頭。結果回傳布林值。position 可以指定開始搜尋的索引值。預設值為 0。

const str = "One Punch Man!!";             
const result1 = str.startsWith('One');    //true
const result2 = str.includes('One', 4);   //false

String.prototype.endsWith(target, length)

檢查是否以 target 結尾。結果回傳布林值。length 可以指定符合的長度。預設值為字串實體的長度。

const str = "One Punch Man!!";             
const result1 = str.endsWith('Man!!');     //true
const result2 = str.endsWith('Main!!', 2); //false

String.prototype.repeat(count)

重複 count 的次數並回傳新的字串。

const result = 'Man!'.repeat(3);  //Man!Man!Man!

樣板字面值(Template Literals)

這是ES2015中嶄新的特性。透過``包覆,就能將運算式或變數和字串結合起來。另外也能支援字串的換行,成為多行字串。不僅可以提升可讀性,在撰寫上也輕鬆許多!

內崁變數

使用 ${...} 將變數、運算式、函式等包覆,並置於想放的位置上。

// ES5
var x=1, y=2;
const resultStr = "x加y等於:" + (x + y) + "。";

// ES2015
let x=1, y=2;
const resultStr = `x加y等於:${x + y}。`;

/* output:
x加y等於:3
*/

多行字串

// ES5
// 需要在換行處加 \n
console.log("我最愛的動畫是: \n"+"One Punch Man!!");

//ES2015
console.log(`我最愛的動畫是:
One Punch Man!!
`);

/* output:
我最愛的動畫是:
One Punch Man!!
*/

小結

字串處理的部份,在 ES2015 中還有推出其他的擴充方法跟極值處理。這部分因為相對來說比較不常使用,有興趣的一樣可以前往參考資源查看喔!

參考資源


上一篇
ES2015(ES6) - number 、 Math
下一篇
ES2015(ES6) - Array
系列文
從ES到ESNext - 30天輕鬆掌握ECMAScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言