通用 JavaScript 手冊/資料型別 - 字串
外觀
讓我們使用字串文字建立一個以字串為值的變數;我們可以用雙引號和單引號括住字串(儘管在大多數語言中,字串用雙引號括住,字元用單引號括住)。
str = "Hello, ";
我們可以使用 '+' 運算子連線字串。讓我們將字串 "world" 新增到變數 'a' 中的字串。
str = str + "world!"; // Hello, world!
任何字串都有一個 'length' 屬性,其中包含字串中字元的數量。
str.length; // 13
String.split([separator]) - 返回透過用 **separator** 分隔 **String** 獲得的子字串陣列。如果 **separator** 未定義,則 **separator** = ","。
names = "Artem,Michail,Nicholas,Alexander";
listOfNames = names.split(','); //Split string to list of strings
twoNames = names.split(',',2); //Split with limit
我們可以使用 substr(index,len) 和 substring(indexA,indexB) 方法從字串中獲取子字串。第一個返回從 'index' 開始的長度等於 len 的子字串。第二個返回從 indexA 到 indexB 的子字串。
a = "Hello world!";
first = a.substr(0,5); //Hello
second = a.substring(6,11); // world
我們還可以使用 charAt 函式獲取某個位置的字元。
a = "Hello world!";
b = a.charAt(2); //e
我們還可以使用 indexOf 和 lastIndexOf 方法獲取字串中某個子字串的位置。這兩個函式都有兩個引數,但只有第一個引數是必需的:要搜尋的字串和從哪個位置開始搜尋字串。indexOf 返回子字串的第一個位置,lastIndexOf 返回子字串的最後一個位置。如果未找到子字串,則這兩個函式都返回 -1。
a = "Hello world";
b = a.indexOf('o',5); // 7
c = a.lastIndexOf('l'); // 9