Strings

Quotes

// recap
let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;

// backtick can put expression
function sum(a, b) {
  return a + b;
}

alert(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3.

// span multiple lines
let guestList = `Guests:
 * John
 * Pete
 * Mary
`;

alert(guestList); // a list of guests, multiple lines

// error
let guestList = "Guests:  // Error: Unexpected token ILLEGAL
  * John";

Special characters

Character

Description

\b

Backspace

\f

Form feed

\n

New line

\r

Carriage return

\t

Tab

\uNNNN

A unicode symbol with the hex code NNNN, for instance \u00A9 – is a unicode for the copyright symbol ©. It must be exactly 4 hex digits.

\u{NNNNNNNN}

Some rare characters are encoded with two unicode symbols, taking up to 4 bytes. This long unicode requires braces around it.

用 \ 使用特殊符號

String length

.length 是一個物件屬性,不是方法因此不需要加 (),返回 string 的長度。

Accessing characters

取得特定位置的字母可以使用 2 種方法,第 1 個直接在字串後加上 [..],第 2 種使用 .charAt() 方法; 2種辦法的差異在沒有東西返回的時候,[...] 返回 undefined, .charAt() 返回空字串。

Strings are immutable

Changing the case

Searching for a substring

str.indexOf 返回尋找字串的位置。

str.lastIndexOf(substr, position)

The bitwise NOT trick

includes, startsWith, endsWith 檢查字串是否有子字串,返回布林值。

Getting a substring

  • str.slice(start [, end]) 返回開始點到結束點的部分字串

  • str.substring(start [, end]).slice() 一樣,唯一不同開始點可以大於結束點。

  • str.substr(start [, length]) 返回從開始點計算長度的字串

method

selects…

negatives

slice(start, end)

from start to end (not including end)

allows negatives

substring(start, end)

between start and end

negative values mean 0

substr(start, length)

from start get length characters

allows negative start

Which one to choose?

substr(...) 不適寫在核心的 JavaScript 中,他可以在瀏覽器環境執行,其他環境可能不行。大多數都使用 slice(...)。

Comparing strings

  • str.codePointAt(pos) 返回字母的編碼位置

  • String.fromCodePoint(code) 返回編碼位置的字母

Correct comparisons

str.localeCompare(str2) 適用所有瀏覽器,比較字母的大小

  • Returns 1 if str is greater than str2 according to the language rules.

  • Returns -1 if str is less than str2.

  • Returns 0 if they are equal.

Internals, Unicode

Surrogate pairs

Diacritical marks and normalization

Last updated

Was this helpful?