以下內容為學習記錄,可以參考 MDN 原文。
環境
- node v12.18.1
- npm 6.14.5
- vscode 1.46
- Microsoft Edge 83
概念
String 全局對象是一個用於字符串或一個字符序列的構造函數。
使用 “\” 可以轉義字符。
const string1 = "A string primitive";
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`; // 模板字符串
const string4 = new String("A String object");
從 ECMAScript 2015 開始,字符串字面量也可以稱為模板字面量:
`hello world` `hello! world!` `hello ${who}` escape `<a>${who}</a>`
構造函數
String() 創建一個新的 String 對象。 當作為函數而不是構造函數調用時,它執行類型轉換,這通常更有用。
typeof String('Hello world'); // string
typeof new String('Hello world'); // object
獲取字符
有兩種方式可以獲取到字符串中的字符。
return 'cat'.charAt(1) // returns "a"
return 'cat'[1] // returns "a"
比較字符串
let a = 'a'
let b = 'b'
if (a < b) { // true
console.log(a + ' is less than ' + b)
} else if (a > b) {
console.log(a + ' is greater than ' + b)
} else {
console.log(a + ' and ' + b + ' are equal.')
}
String 基礎類型和對象
let s_prim = 'foo'
let s_obj = new String(s_prim)
console.log(typeof s_prim) // Logs "string"
console.log(typeof s_obj) // Logs "object"
長字符串
有兩種方式定義長字符串。
let longString = "This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable."
let longString = "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable."
靜態方法
fromCharCode
String.fromCharCode() 方法返回由指定的 UTF-16 代碼單元序列創建的字符串。
console.log(String.fromCharCode(189, 43, 190, 61));
// expected output: "½+¾="
fromCodePoint
String.fromCodePoint() 靜態方法返回使用指定的代碼點序列創建的字符串。
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));
// expected output: "☃★♲你"
raw
String.raw() 是一個模板字符串的標簽函數,是用來獲取一個模板字符串的原始字符串的,比如說,占位符(例如 ${foo})會被處理為它所代表的其他字符串,而轉義字符(例如 \n)不會。
// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`C:\Development\profile\aboutme.html`;
console.log(`The file was uploaded from: ${filePath}`);
// expected output: "The file was uploaded from: C:\Development\profile\aboutme.html"
實例屬性
除了 prototype,字符串有一個實例屬性 length,它代表了字符串的長度。
var x = "Mozilla";
var empty = "";
console.log("Mozilla is " + x.length + " code units long");
/* "Mozilla is 7 code units long" */
console.log("The empty string is has a length of " + empty.length);
/* "The empty string is has a length of 0" */