目錄
- includes(), startsWith(), endsWith()
- repeat()
- 模板字符串
1. includes(), startsWith(), endsWith()
- includes():返回布爾值,表示是否找到了參數字符串。
- startsWith():返回布爾值,表示參數字符串是否在原字符串的頭部。
- endsWith():返回布爾值,表示參數字符串是否在原字符串的尾部。
let s = 'Hello world';
s.includes('o') // true
s.startsWith('Hello') // true
s.endsWith('!') // true
這三個方法都支持第二個參數,表示開始搜索的位置。
let ss = 'Hello world!';
ss.startsWith('world', 6) // true
ss.endsWith('Hello', 5) // true
ss.includes('Hello', 6) // false
上面代碼表示,使用第二個參數 n 時,endsWith 的行爲與其他兩個方法有所不同。它針對前 n 個字符,而其他兩個方法針對從第 n 個位置直到字符串結束。
2. repeat()
repeat 方法返回一個新字符串,表示將原字符串重複 n 次。
'na'.repeat(2) // 'nana'
'na'.repeat(0) // ''
參數如果是小數,則會被取整
'na'.repeat(2.9); // 'nana'
'na'.repeat(2.1); // 'nana'
如果 repeat 的參數是負數或者 Infinity,會報錯
'na'.repeat(Infinity) //RangeError
'na'.repeat(-1) // RangeError
但是,如果參數是 0 到-1 之間的小數,則等同於 0,這是因爲會先進行取整運算。0 到-1 之間的小數,取整以後等於-0,repeat 視同爲 0。
'na'.repeat(-0.9) // ''
參數NaN等同於 0。
'na'.repeat(NaN) // ""
如果 repeat
的參數是字符串,則會先轉換成數字。
'na'.repeat('na') // ""
'na'.repeat('3') // "nanana"
3. 模板字符串
模板字符串之中還能調用函數。
function fun() {
return 'Hello world';
}
`foo ${fun()} bar`
// foo Hello world bar