javascript中的String類的幾個常用方法備忘

String類有大量的方法。以下列舉幾個常用的

1.CharAt()

 

var oString = new String("lenovo");
alert(oString.charAt(1));    //output "e"

 

 

2.CharCodeAt()

 

   var oString = new String("lenovo");
   alert(oString.charCodeAt(1));  //output "101"

 

    這裏得到的是字符代碼,e對應的是101。

 

3.concat()

 

   用於把一個或者多個字符串連接到String對象的原始值上,返回的是連接後的字符串,但是原始的字符串對象將不發生改變

 

 

var oString = new String("hello");
var oConcatString = oString.concat(" lenovo");
alert(oString);  //output "hello";
alert(oConcatString);   //output "hello lenovo";

 

 

3.indexOf()  和 lastIndexOf()

 

   如果要找某個字符串中是否存在某個字符,就要使用indexOf()方法

 

   這兩個方法的不同是indexOf()方法是從字符串的開頭開始尋找,而lastIndexOf()方法是從字符串的結尾開始尋找。

 

 

var serchString = new String("hello lenovo");
alert(serchString.indexOf("o");  //output 4;
alert(serchString.lastIndexOf("o");   //output 10;

 

 

4.localeCompare()

 

   這個方法對字符串值進行排序,該方法的參數是一個要進行比較的字符串。代碼說明:var oString = new String("ygz");

 

alert(ostring.localeCompare("block");   //output 1,以爲z在b的後面

alert(oString.localeCompare("yero");    //output 0,因爲同是z

alert(oString.localeCompare("zgz");      //output -1,因爲y在z的前面

 

 需要說明的是:localeCompare()方法是區分字母大小寫的,大寫字母在順序上要排在小寫字母之後。

 

5.slice()和substring()

 

   方法命名如果是簡寫了,就全部是小寫,如果是完整的,就會是第二個單詞大寫。(題外話)

 

   這兩個方法都是截取字符串的,但是和concat()方法一樣,只返回操作後的字符串,而不影響原來的字符串

 

   如果參數都是正數,那麼這兩個方法的表現一樣

 

 

var oString = new String("hello lenovo");
alert(oString.slice(3));   //output "lo lenovo"  從第三個位置截取到最後
alert(oString.slice(3,7));   //output "lo l" 從第三個位置截取到第七個位置
alert(oString.substring(3));  // output  same as top;
alert(oString.substring(3,7));   // output  same as top

 

 

   如果是負數,則substring()方法將把負數看作0來處理。代碼如下:

 

 

var oString = new String("hello lenovo");
alert(oString.slice(-3));  //output "ovo"
alert(oString.substring(-3)); //output "hello lenovo"
alert(oString.slice(3,-4));  //output "lo le"
alert(oSTring.substring(3,-4)); //output "hel"

 

6.toLowerCase(),toLocaleLowerCase() 和 toUpperCase(),toLocaleUpperCase()

 

   前兩者是把字符串轉換爲小寫字母,後兩者是把字符串轉換爲大寫字母。

 

   locale是區域字樣的意思,一般情況下不必區分。

 

 

發佈了21 篇原創文章 · 獲贊 0 · 訪問量 1604
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章