String Object

對於字串物件的操作

by Joseph Chiang

JavaScript

// 宣告一個字串變數
// var str = "Today is a huge day.";

// 其實也可以寫成很物件導向的... 
var str = new String("Today is a huge day.");

// 取得字串物件的長度
document.write("str.length = " + str.length + "<br>");

// 取代字串
document.write("str.replace('huge', 'tiny') = " + str.replace('huge', 'tiny') + "<br>");

// 取得內部某字串的索引位置
document.write("str.indexOf('day') = " + str.indexOf('day') + "<br>");

// 從索引值 x 的位置開始取 y 個字
document.write("str.substr(3, 8) = " + str.substr(3, 8) + "<br>");

// 從索引值 x 取到索引值 y
document.write("str.substring(3, 10) = " + str.substring(3, 10) + "<br>");

// 從字串結尾開始搜尋內部特定字串(仍然是從索引值 0 起算)
var url = "http://tw.yahoo.com/i/image/xyz?g=x";
document.write("url.lastIndexOf('/')" + url.lastIndexOf("/") + "<br>");

// 將字串分割為陣列
var words = str.split(" ");
document.write("str.split(' ') = " + str.split(' ') + "<br>");