字符串處理

1.charAt,charCodeAt
var str:String = "hello world!";
for (var i:int = 0; i < str.length; i++)
{
        trace(str.charAt(i), "-", str.charCodeAt(i));
}
//charAt(i)得到每個字符.charCodeAt(i)得到字符的編碼.
2.substr() 和 substring() 返回字符串的一個子字符串。
var str:String = "Hello from Paris, Texas!!!";
trace(str.substr(11,15)); // 輸出:Paris, Texas!!!
trace(str.substring(11,15)); // 輸出:Pari
3.slice()
slice() 方法的功能類似於 substring() 方法。但可以使用負整數作爲參數,
此時字符位置將從字符串末尾開始向前算起,

var str:String = "Hello from Paris, Texas!!!";
trace(str.slice(11,15)); // 輸出:Pari
trace(str.slice(-3,-1)); // 輸出:!!
trace(str.slice(-3,26)); // 輸出:!!!
trace(str.slice(-3,str.length)); // 輸出:!!!
trace(str.slice(-8,-3)); // 輸出:Texas
4.indexOf() 和 lastIndexOf()
查找匹配子字符串的字符位置
indexOf() 和 lastIndexOf()在字符串內查找匹配的子字符串,

var str:String = "The moon, the stars, the sea, the land";
trace(str.indexOf("the")); //輸出:10

var str:String = "The moon, the stars, the sea, the land"
trace(str.indexOf("the", 11)); // 輸出:21

lastIndexOf() 方法在字符串中查找子字符串的最後一個匹配項:

var str:String = "The moon, the stars, the sea, the land"
trace(str.lastIndexOf("the")); // 輸出:30

如爲 lastIndexOf() 方法提供了第二個參數,搜索將從字符串中的該索引位置反向(從右到左)進行:

var str:String = "The moon, the stars, the sea, the land"
trace(str.lastIndexOf("the", 29)); // 輸出:21
5.split()
創建由分隔符分隔的子字符串數組
split() 方法創建子字符串數組,該數組根據分隔符進行劃分。

var queryStr:String = "first=joe&last=cheng&title=manager&StartDate=3/6/65";
var params:Array = queryStr.split("&", 2); // params == ["first=joe","last=cheng"]

split() 方法的第二個參數是可選參數,該參數定義所返回數組的最大大小。

另 split還支持正則表達式作爲分隔符處理,這裏不涉及正則處理

在字符串中查找模式並替換子字符串
match() 和 search() 方法可查找與模式相匹配的子字符串。    
replace() 方法可查找與模式相匹配的子字符串並使用指定子字符串替換它們。    
search() 方法返回與給定模式相匹配的第一個子字符串的索引位置。


var str:String = "The more the merrier.";
trace(str.search("the")); // 輸出:9

對於search,match,replace都支持正則表達式匹配處理
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章