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本來就可以用正則替換。

          引用

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

          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需要動態(tài)生成時更適合使用這種方式。

          擴展一下:
          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函數(shù)是在web端實現(xiàn)的還是在WEB服務器端執(zhí)行的,還有就是Replace執(zhí)行對于服務器環(huán)境有沒有要求!

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


          網站導航:
           
          主站蜘蛛池模板: 延川县| 南康市| 安义县| 林芝县| 女性| 洛浦县| 离岛区| 蓬溪县| 临西县| 内黄县| 阿拉善左旗| 出国| 满洲里市| 惠州市| 祁连县| 芷江| 霸州市| 灵璧县| 平原县| 繁昌县| 太仆寺旗| 盖州市| 隆尧县| 上饶县| 金山区| 司法| 山阳县| 洛宁县| 崇明县| 册亨县| 泰顺县| 儋州市| 天水市| 泸州市| 临桂县| 双牌县| 高邑县| 乐昌市| 开鲁县| 焉耆| 纳雍县|