上一節(jié)中怔接,我們學習了模板字符串和標簽?zāi)0澹@一節(jié)泼各,我們接著來看一下ES6還對字符串添加了哪些新特性知牌。
repeat() 函數(shù)
includes() 函數(shù)
startswith() 函數(shù)
endswith() 函數(shù)
codePointAt() 函數(shù)
String.fromCodePoint( ) 函數(shù)
String.raw() 函數(shù)
repeat() 函數(shù)
將目標字符串重復(fù)n次,返回新的字符串:
cons tname = 'zzq';
const nameR = name.repeat(3);
console.log(nameR); // zzqzzqzzq
includes() 函數(shù)
判斷字符串中是否含有指定的字符串站超,返回值是boolean類型:
const str = "my name is zzq";
str.includes('zzq'); // true
str.includes('s'); // false
includes(參數(shù)1, 參數(shù)2) 可以傳入兩個參數(shù):
參數(shù)1:要查找的字符串荸恕,
參數(shù)2:指定開始查找的位置
const str = "my name is zzq";
str.includes('m'); // true
str.includes('m', 8); // false
startswith() 函數(shù)
startswith(參數(shù)1, 參數(shù)2):
判斷目標字符串是否以指定字符串開頭
參數(shù)1:指定字符串,
參數(shù)2(可選):開始搜索的位置
const str = "jintian tianqi zhenhao";
str.startsWith('jin'); // true
str.startsWith('tianqi '); // false
str.startsWith('tianqi ',8); // true
endswith() 函數(shù)
和startswith的用法一樣死相,用來判斷目標字符串是否以指定字符串結(jié)尾融求。同樣也可以使用兩個參數(shù)。廢話不多說算撮,直接上代碼就可以了:
const str = "jintian tianqi zhenhao";
str.endsWith('zhenhao'); // true
str.endsWith('qi', 14); // true
str.endsWith('an', 7); // true
需要注意的是生宛,第二個參數(shù)是代表指在前n個字符里判斷。
codePointAt() 函數(shù)
在js中肮柜,一個字符需要2個字節(jié)存儲陷舅,需要4個字節(jié)存儲的js認為它是2個字符。
const str = "??";
console.log(str.length); // 2
例如漢字 "??"的長度是2审洞,代表占兩個字符莱睁,但是js無法處理。。所以ES6添加了codePointAt()函數(shù)用來處理4個字節(jié)的字符仰剿。
const str = "??";
str.codePointAt(str); // 134071
134071是 "??"的碼點的十進制數(shù)创淡,轉(zhuǎn)換成16進制就是20bb7,其對應(yīng)的Unicode編碼則是\u20bb7南吮。
(這一塊我理解的不是很好琳彩,建議可以看下這篇文章細致的了解:es6學習筆記-字符串的擴展_v1.0)
String.fromCodePoint( ) 函數(shù)
和codePointAt()相反,該函數(shù)是根據(jù)傳進的碼點返回對應(yīng)的字符部凑,比如上邊的 "??" 的碼點是134071:
String.fromCodePoint(134071); // ??
String.raw() 函數(shù)
我們先來看一下代碼:
`hello\nworld`; // 輸出:hello換行world
String.raw`hello\nworld`; // 輸出:hello\nworld
從上邊的代碼中露乏,可以很清晰地看到String.raw的作用:把已加工的字符串轉(zhuǎn)換為原始字符串。
最后涂邀,跟大家分享一下我的個人博客地址:http://javascript404.com
歡迎你的到來 ~ ~ ???