javascript string對象方法總結
1.anchor()
用于創建html錨,也就是a標簽,()中可以帶參數,是a標簽的name屬性值。
var string="hello world";
document.writeln(string.anchor("name屬性值"));
2.charAt()
用于尋找特定索引值的字符,()中的參數是字符串中某一字符的索引值,注意charAt()只能返回一個字符。
var string="hello world";
document.writeln(string.charAt(4));//o
3concat()
用于拼接字符串,()中的參數是一個或多個字符串,注意:一般字符串拼接我們用+就可以實現。
var string1="hello ";
var string2="world";
document.writeln(string1.concat(string2));
4.indexOf()
用于尋找某一字符或字符串第一次出現的索引值,()中的第一個參數是要尋找的字符串或字符,第二個參數是要從哪個索引位置尋找,如果省略則從頭向尾部尋找,沒有找到就會返回-1.注意:indexOf()對大小寫敏感
var string1="hello world";
var string2="world";
document.writeln(string1.indexOf(string2,3));//6
var string1="hello world";
var string2="word";
document.writeln(string1.indexOf(string2,3));//-1
5.lastIndexOf()
用于尋找某一字符或字符串最后一個出現的索引值,()中的第一個參數是要尋找的字符串或字符,第二個參數是要從哪個索引位置尋找,如果省略則從尾部向頭部尋找,沒有找到就會返回-1.注意:indexOf()對大小寫敏感
var string1="hello world";
var string2="world";
document.writeln(string1.lastIndexOf(string2,5));//-1
6.match()
用于尋找匹配的某一字符或字符串,通常和正則表達式配合使用,如果正則表達式是全局搜索,則返回所有匹配的字符或字符串的數組。
var string="123123123";
document.writeln(string.match(/2/g));//2,2,2
7.replace()
用于替換某一字符或字符串,()中的第一個參數是替換前的字符串,可以是字符串或正則表達式,第二個參數是替換后的字符串,只能是字符串。
var string="hello world";
document.writeln(string.replace("hello","hi"));
8.search()
用于查找第一個匹配正則表達式的字符串的索引值,注意:1.search()沒有全局搜索能力,就算寫了g。2.search()只能搜索第一個匹配的字符串位置。3.對大小寫敏感。
var string="hello world";
document.writeln(string.search("hello"));
9.slice()
用于截取匹配的字符串,()中的參數都是索引值,而且可以為負數。返回的字符串包括第一個參數的字符,不包括第二個參數的字符。
var string="hello world";
document.writeln(string.slice(3,5));//lo
10.split()
將字符串轉化成數組。()中的第一個參數為按什么截取,第二個參數是截取多少個。
var string="hello world";
document.writeln(string.split(" "));//hello,world
11.substr()
用于截取匹配的字符串,()中一個參數是開始匹配的索引值,第二個參數是要截取的長度。
var string="hello world";
document.writeln(string.substr(2,6));//llo wo
12.substring()
和slice()用法一樣,只不過substring()的參數不接受負值,而且如果start>end,他會將這倆個參數自動換位。
13.valueOf()
用于檢驗調用該方法的對象是不是string對象。
來自:http://www.cnblogs.com/iwebkit/p/6504583.html