今天離職了,挺捨不得的,現在下班了,把自己寫的讀書筆記發一篇
1、模板字符串
模板字符串主要便於字符串拼接,可以把變量插入字符串中;
代碼如下:
let str1 = "hello";
let str2 = "world";
let str3 = `str1 is ${str1},str2 is ${str2}`;
以上就是模板字符串的基本用法,當然使用的時候需要注意幾點
定義多行字符串
let str1 = "hello";
let str2 = "world";
let str3 = `str1 is ${str1},
str2 is ${str2}`;
直接換行即可,因爲所有的空格縮進都會保留,代碼上換了行,控制檯輸出的時候也會換行。
${ }中可以寫js表達式
比如:
let a = 1;
let b = 2;
let c = `c is ${a+b}`;
${ }中可以寫對象的屬性
let obj = {"a":1,"b":2};
let str4 = `the str4 is ${obj.a+obj.b}`;
${ }中可以進行函數的調用
function getRes() {
return 1;
}
let str5 = `getRes is ${ getRes() }`;
2、標籤模板
模板指的是字符串模板,用反引號定義的字符串;而標籤是處理模板字符串的函數。
let str1 = "hello";
let str2 = "world";
tagStr`str1 is ${str1},str2 is ${str2}`;
function tagStr(arr, v1, v2){
console.log(arr, v1, v2);
}
’tagStr`str1 is ${str1},str2 is ${str2}`;’這個就是標籤模板
3、repeat函數
該函數就是將字符串重複N次,返回一個新的字符串,不影響目標字符串。
4、includes函數
該函數是用來判斷字符串中是否含有指定的字符串,返回true表示含有和false表示未含有。第二個參數選填,表示開始搜索的位置。
5、 startsWith函數
該函數是用來判斷指定的子字符串是否出現在目標字符串的開頭位置,第二個參數選填,表示開始搜索的位置。
name.startsWith('D')
true
name.startsWith('a')
false
name.startsWith('a',1)
true
6、endsWith函數
該函數是用來判斷子字符串是否出現在目標字符串的尾部位置,第二個參數選填,表示針對前N個字符。
name.endsWith('a')
false
name.endsWith('r')
true
name.endsWith('y', 3)
true
7、String.raw函數
該函數返回字符串最原始的樣貌,即使字符串中含有轉義符,它都視而不見,直接輸出。
未經過該函數處理是這樣的:
因爲\n會被識別爲換行符,實現換行效果,而經過String.raw( )的同一個字符串的結果是: