JavaScript中的string對象及方法

來源:互聯網
上載者:User

標籤:script   substring   java   new   dex   arc   sub   轉換   case   

string對象

string對象的兩種建立

var a="hello";

var b=new String("hello");

 

  //下面是方法

 //charAt()根據下標 找字串中的字元

     alert(a.charAt(3));//根據下標返回字串某個字元

     alert(a.charAt(10));//空的,找不到這個下標

 

    //charCodeAt()返回指定位置的字元

          var a="Hello world!Hello world!";

          var d="這是一個字串";

          alert(a.charCodeAt(1));//101

     alert(d.charCodeAt(3));//26465

  

     //String.fromCharCode()利用unicode編碼返回一個字串

     alert(String.fromCharCode(65,66,67));//

 

     //concat()用於串連一個或多個字串 不改變原數組

           var a="Hello world!Hello world!";

         var b="日照香爐生紫煙";

         var c="不及汪倫送我情";

         alert(a.concat(b,c))

   

 //search()找到要匹配的字串,如果找到,返回第一次匹配的下標,如果未找到,返回-1

     var c="123456789";

     alert(c.search("567"));//4

     alert(c.search("5671"));//-1

 

 //replace()用一些字替換另一些字元

     var d="小黃是條狗,小黃很帥";

     var e=d.replace("小黃","小黑");//小黃變小黑,只變第一次

    var e=d.replace(/小黃/g,"小黑")//字串內的都改變

    alert(e);

 

    //split()用於把一個字串分割為字串數組,原數組不變

     var a="hello world!";

          alert(a.split(""));

          alert(a.split("o"));//hell, w,rld

        

  //indexOf()返回某個指定字元在字串中首次出現的位置

    var a="hello world!";

    alert(a.indexOf("o"));//4

    alert(a.indexOf("p"));//-1  沒有搜到出-1

 

     //lastIndexOf()從後向前搜尋

    var a="hello world!";

         alert(a.lastIndexOf("o"));//7

        

     //Match()

      var a="Hello world!Hello world!";

      alert(‘world‘)//找到第一個就不找了5

      alert(a.match(/world/g));//Regex(全域尋找)

   

    //slice()可提取字串某個部分  可負數

    var a="Hello world!Hello world!";

    alert(a.slice(5,13));//要第一個下標,不要第二個下標

    alert(a.slice(-15,-7));

 

   //substring()與slice一樣,但不接受負數

    var a="Hello world!Hello world!";

    alert(a.substring(4,12));

      alert(a.substring(-3,-1));//啥也沒有

 

   //substr()截取從指定下標開始,指定數目的字元

    var a="Hello world!Hello world!";

    alert(a.substr(4,6));//從下標4開始向後截取6個

        

   //toLowerCase()將字串轉換為小寫

    var a="Hello world!Hello world!";

         alert(a.toLowerCase());

        

   //toUpperCase()將字串轉換為大寫

         var a="Hello world!Hello world!";

         alert(a.toUpperCase());

 

JavaScript中的string對象及方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.