JavaScript 字串(String)物件

String 物件用於處理已有的字元塊。


JavaScript 字串

一個字串用於儲存一系列字元就像 "John Doe".

一個字串可以使用單引號或雙引號:

例項

var carname="Volvo XC60";
var carname='Volvo XC60';

你使用位置(索引)可以訪問字串中任何的字元:

例項

var character=carname[7];

字串的索引從零開始, 所以字串第一字元為 [0],第二個字元為 [1], 等等。

你可以在字串中使用引號,如下例項:

例項

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

或者你可以在字串中使用轉義字元(\)使用引號:

例項

var answer='It\'s alright';
var answer="He is called \"Johnny\"";

嘗試一下 ?


字串(String)

字串(String)使用長度屬性length來計算字串的長度:

例項

var txt="Hello World!";
document.write(txt.length);

var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);

嘗試一下 ?

在字串中查詢字串

字串使用 indexOf() 來定位字串中某一個指定的字元首次出現的位置:

例項

var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");

嘗試一下 ?

如果沒找到對應的字元函式返回-1

lastIndexOf() 方法在字串末尾開始查詢字串出現的位置。


內容匹配

match()函式用來查詢字串中特定的字元,並且如果找到的話,則返回這個字元。

例項

var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));

嘗試一下 ?


替換內容

replace() 方法在字串中用某些字元替換另一些字元。

例項

str="Please visit Microsoft!"
var n=str.replace("Microsoft","itread01");

嘗試一下 ?


字串大小寫轉換

字串大小寫轉換使用函式 toUpperCase() / toLowerCase():

例項

var txt="Hello World!"; // String
var txt1=txt.toUpperCase(); // txt1 文字會轉換為大寫
var txt2=txt.toLowerCase(); // txt2 文字會轉換為小寫

嘗試一下 ?


字串轉為陣列

字串使用split()函式轉為陣列:

例項

txt="a,b,c,d,e" // String
txt.split(","); // 使用逗號分隔
txt.split(" "); // 使用空格分隔
txt.split("|"); // 使用豎線分隔

嘗試一下 ?


特殊字元

Javascript 中可以使用反斜線(\)插入特殊符號,如:撇號,引號等其他特殊符號。

檢視如下 JavaScript 程式碼:

var txt="We are the so-called "Vikings" from the north.";
document.write(txt);

在JavaScript中,字串的開始和停止使用單引號或雙引號。這意味著,上面的字串將被切成: We are the so-called

解決以上的問題可以使用反斜線來轉義引號:

var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);

JavaScript將輸出正確的文字字串:We are the so-called "Vikings" from the north.

下表列出其他特殊字元,可以使用反斜線轉義特殊字元:

程式碼 輸出
\' 單引號
\" 雙引號
\\ 斜杆
\n 換行
\r 回車
\t tab
\b 空格
\f 換頁


字串屬性和方法

屬性:

  • length
  • prototype
  • constructor

方法:

  • charAt()
  • charCodeAt()
  • concat()
  • fromCharCode()
  • indexOf()
  • lastIndexOf()
  • match()
  • replace()
  • search()
  • slice()
  • split()
  • substr()
  • substring()
  • toLowerCase()
  • toUpperCase()
  • valueOf()

更多方法與屬性介紹可以參考:JavaScript String 物件