JavaScript String (字串)
在 JavaScript 字串是用單引號 ' 或雙引號 " 包住的字。
用單引號
' 或雙引號 " 都是一樣的,沒有特別。例如:
const str = 'string text';
const str2 = 'string text';
const str3 =
'中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית';
特殊字元 (Special Characters)
因為字串必須包在單引號或雙引號裡面,但是要特別注意的雙引號裡面不能有雙引號、單引號裡面不能有單引號。
例如下面這些都會發生錯誤:
const str = 'Mike's pet.';
const str2 = "This is a "book".";
你可以改成這樣就會正確,因為雙引號裡面可以有單引號,或單引號裡面可以有雙引號:
const str = "Mike's pet.";
const str2 = 'This is a "book".';
或是使用跳脫字元 (escape character) 反斜線 (backslash) \,來跳脫引號:
// Mike's pet.
const str = "Mike's pet.";
// This is a "book".
const str2 = 'This is a "book".';
跳脫字元 \ 可以用來跳脫這些特殊字元:
| 特殊符號 | 表示的符號 |
|---|---|
| \0 | NULL 字元 |
| ' | 單引號 |
| " | 雙引號 |
| \ | 反斜線 |
| \n | 換行符號 |
| \r | carriage return 回車鍵 |
| \t | tab |
| \v | vertical tab |
| \b | backspace |
| \f | form feed |
| \uXXXX | unicode codepoint |
字串相加 (String Concatenation)
我們可以用 + 和 += 運算子來將多個字串接起來變成一個。
用法例如:
let str = 'hel' + 'lo';
// 輸出 'hello'
console.log(str);
const name = 'Mike';
let str2 = str + ' ' + name;
// 輸出 'hello Mike'
console.log(str2);
// str2 += '!' 意思同 str2 = str2 + '!'
str2 += '!';
// 輸出 'hello Mike!'
console.log(str2);
多行字串 / 換行
有時候會遇到有非常長的字串讓你難以閱讀,例如:
const longString =
'This is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable.';
但你可以用字串相加的技巧,讓你的字串更好閱讀:
const longString =
'This is a very long string which needs ' +
'to wrap across multiple lines because ' +
'otherwise my code is unreadable.';
或是可以在字串最後面加上反斜線 \ 表示字串會從下一行接續下去:
const longString =
'This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.';
\ 後面除了換行符號,不能再有任何字元包含空白。
上面三種字串寫法都會得到一樣的字串結果喔!
樣板字面值 (Template Literals)
在 ES6 之後,JavaScript 新增了使用反引號 ` (Backtick) 來包住的樣板字面值,讓我們更方便的處理字串相加和多行字串。
變數插入 (String Interpolation):
const name = 'Mike';
// 以前要用 + 號
// const str = 'Hello ' + name;
// 現在可以用 ${} 直接插入變數
const str = `Hello ${name}`;
多行字串 (Multiline Strings):
// 可以直接換行,不需要用 \ 或 +
const longString = `This is a very long string which needs
to wrap across multiple lines because
otherwise my code is unreadable.`;
詳細請參考 ES6 Template Literals。
String() 函數 - 型別轉換
數字轉字串
String(123); // '123'
String(100 + 23); // '123'
const x = 123;
String(x); // '123'
布林值轉字串
String(true); // 'true'
String(false); // 'false'
字串相等
我們可以用 === 或 == 運算子來判斷兩個字串是否相等:
const str = 'hello world';
// 會輸出 'equal'
if (str === 'hello world') {
console.log('equal');
}
字串比對會逐字元比較,看兩個字串是否完全一樣。
相對的,我們可以用 !== 或 != 運算子來判斷兩個字串是否不相等:
const str = 'hello world';
// 會輸出 'not equal'
if (str !== 'hello Mars') {
console.log('not equal');
}