js的replace

          Posted on 2008-07-10 17:44 追夢人 閱讀(1874) 評論(1)  編輯  收藏 所屬分類: Javascript
          "hand hand hand"想變換為"hand.gif hand.gif hand.gif"
          開始用
          str=str.replace("hand","hand.gif");
          輸出:hand.gif hand hand
          只替換了一次。。。:(
          想到用正則,因為replace本來就可以用正則替換。

          引用

          返回根據正則表達式進行文字替換后的字符串的復制。

          stringObj.replace(rgExp, replaceText)



          于是寫
          str = str.replace(/hand/,"hand.gif")
          無效。。。
          全部替換要加g,
          str = str.replace(/hand/g,"hand.gif")
          還是不行:(

          參考了JavaScript的replace方法與正則表達式結合應用講解這篇文章后,終于明白,原來要用()括起來,才會替換()里的東東。正確的寫法如下:
          str = "hand hand hand";
          str=str.replace(/(hand)/g,"hand.gif");  
          document.write(str);  
          正確輸出:hand.gif hand.gif hand.gif。

          JS的正則另一種寫法是使用RegExp:
          如str=str.replace(/(hand)/g,"hand.gif");
          等同于:
          reg = new RegExp("(hand)","g");
             str = str.replace(reg,'hand.gif');
          reg需要動態生成時更適合使用這種方式。

          擴展一下:
          str = "hand'( hand'( hand'(";
          str=str.replace(/(hand\'\()/g,"hand.gif");  
          document.write(str);

          str = 'hand\'( hand\'( hand\'(';
          str=str.replace(/(hand\'\()/g,"hand.gif");  
          document.write(str);

          Feedback

          # re: js的replace  回復  更多評論   

          2013-07-18 15:09 by beseen
          這個Replace函數是在web端實現的還是在WEB服務器端執行的,還有就是Replace執行對于服務器環境有沒有要求!

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 金堂县| 九龙城区| 乐业县| 治多县| 天柱县| 阿勒泰市| 梁平县| 广安市| 林芝县| 呼图壁县| 固镇县| 海南省| 陵川县| 临夏县| 自贡市| 汝城县| 江川县| 府谷县| 衡阳市| 芜湖县| 紫云| 青川县| 山西省| 达州市| 新巴尔虎右旗| 从江县| 虹口区| 封丘县| 清河县| 漯河市| 萝北县| 邓州市| 澄迈县| 武乡县| 长丰县| 安陆市| 河南省| 栾川县| 安义县| 阳谷县| 姜堰市|