關於JavaScript處理字串的常見操作

來源:互聯網
上載者:User

標籤:rip   bsp   txt   substr   取出   操作   參考   ||   存在   

//給定一個字串例如:“abaasdffggghhjjkkgfddsssss3444343”;

1、 字串的位元組長度

參考代碼:

document.write(txt.length+"<br/>");document.write("<br/>");

2、 取出指定位置的字元,如:0,3,5,9 等

參考代碼:

for (var i=0;i<txt.length;i++){    if(i==0 || i==3 || i==5 || i==9){        document.write("位置為"+i+"字元是:"+txt.substr(i,1)+"<br/>");    }}document.write("<br/>");

3、 尋找指定字元是否在以上字串中存在,如:i,c ,b 等

參考代碼:

if(txt.indexOf("i") !=-1){    document.write("i在字串中存在<br/>");}else{    document.write("i在字串中不存在<br/>");}if(txt.indexOf("c") !=-1){    document.write("c在字串中存在<br/>");}else{    document.write("c在字串中不存在<br/>");}if(txt.indexOf("b") !=-1){    document.write("b在字串中存在<br/>");}else{    document.write("b在字串中不存在<br/>");}

4、 替換指定的字元,如:g 替換為 22,ss 替換為 b 等操作方法

參考代碼:

document.write(txt);var txtReg=/[g]/g;  //Regex的用法var txtValue=txt.replace(txtReg,"22");document.write("<br/>");document.write(txtValue);document.write("<br/>");document.write("<br/>");document.write(txt);var txtReg=/[s]{2}/g;var txtValue=txt.replace(txtReg,"b");document.write("<br/>");document.write(txtValue);document.write("<br/>");

5、 找出以上字串中出現次數最多的字元和出現的次數

參考代碼:

var json = {};for (var i=0;i<txt.length;i++){    if (!json[txt.charAt(i)]){        json[txt.charAt(i)] = 1;    } else{        json[txt.charAt(i)]++;    }}var char=‘‘;var num=0;for (var key in json){    if(json[key]>num){        char = key;        num = json[key];    }}document.write(txt+"出現次數最多的字元為"+char+"且次數為:"+num);

 

關於JavaScript處理字串的常見操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.