字元串的for of
ES6 為字元串添加了周遊器接口,使得字元串可以被for...of循環周遊。
const str='abcd';
for(let s of str){
console.log(s)
}
✨模闆字元串
//es5
var name='小明',
age=18;
console.log('我叫'+name+'今年'+age+'歲')
//es6
console.log(`我叫${name}今年${age}歲`);
注意:模闆字元串使用,即不是雙引号
``
,也不是單引号
""
''
通常在鍵盤左上角
``
按鍵下方
ESC
新增字元串方法
String.includes(searchStr)
- 描述:判斷是否含有目标字元串searchStr
-
{ const str='hello world'; console.log(str.includes('hello'));//true }
String.startsWith(searchStr,position?)
- 描述:判斷字元串是否以searchStr開頭,第二個參數position(可選)預設為0,表示從第幾個字元開始向後判斷
-
{ const str='hello world'; console.log(str.startsWith('hello'));//true console.log(str.startsWith('abc'));//false console.log(str,startsWith('hello',1));//false console.log(str,startsWith('world',6));//true }
String.endsWith(searchStr,position?)
- 描述:判斷字元串是否以searchStr結尾,同樣第二個參數position(可選)預設為原字元串長度,表示從第幾個字元開始向前判斷
-
{ const str='hello world'; console.log('endsWith', str.endsWith('world'));//true console.log('endsWith', str.endsWith('abc'));//false console.log('endsWith', str.endsWith('world',11));//true console.log('endsWith', str.endsWith('hello', 5));//true console.log('endsWith', str.endsWith('hello', 7));//false }
String.repeat(n)
- 描述:repeat方法傳回一個新字元串,表示将原字元串重複n次。
let str='abcd';
str=str.repeat(3);
console.log(str);//abcdabcdabcd
ES2017 引入了字元串補全長度的功能。如果某個字元串不夠指定長度,會在頭部或尾部補全。
1.String.padStart(length,fillStr?)頭部補全
2.String.padEnd(length,fillStr?) 尾部補全
- length: 補全後的字元串長度
- fillstr: 用于填充的字元串,預設為空格
let str='5678'
console.log(str.padStart(8,'abc'));//abca5678
console.log(str.padEnd(8,'abc'));//5678abca
執行個體
//提示日期
let str = '08-12'
console.log(str.padStart(10, 'yyyy-MM-dd'));//yyyy-08-12
ES2019 對字元串執行個體新增了trimStart()和trimEnd()這兩個方法。它們的行為與trim()一緻,trimStart()消除字元串頭部的空格,trimEnd()消除尾部的空格。它們傳回的都是新字元串,不會修改原始字元串。
const s = ' abcd ';
s.trim() //"abcd"
s.trimStart() //"abc "
s.trimEnd() //" abc"
"你的指尖,擁有改變世界的力量! "
歡迎關注我的個人部落格:https://sugarat.top