Re: [問題] javascript replace的正規表達式

看板Ajax作者 (沉默是金。)時間15年前 (2010/08/11 22:44), 編輯推噓4(406)
留言10則, 4人參與, 最新討論串2/2 (看更多)
※ 引述《BA0 (寶)》之銘言: : 小弟希望把一個字串內的幾個特定內容換成另外幾個 : 文字表達比較混亂-_- : 就是象 str1="sfjoabysfjslsfdctjpsg" : 想把其中的a都換成@,s都換成$ : 我知道可以用 : str1=str1.replace(/a/g,"@"); : str1=str1.replace(/s/g,"$"); : 但是我想問用一次replace完成,應該怎麼寫 : 如果字串很長,跑兩次很低效 : 感謝大大回答 你可以這樣寫 str1=str1.replace(/[as]/g,function(token){ if(token == "s") return "@"; else return "$"; }); token會拿到pattern match到的字 -- I am a person, and I am always thinking . Thinking in love , Thinking in life , Thinking in why , Thinking in worth. I can't believe any of what , I am just thinking then thinking , but worst of all , most of mine is thinking not actioning... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.82.145.85

08/11 23:18, , 1F
不過經過實驗看起來用function反而會造成overhead
08/11 23:18, 1F

08/11 23:18, , 2F

08/11 23:19, , 3F
基本上這種問題是不是有需要去作最佳化是by case 的 :~
08/11 23:19, 3F

08/11 23:30, , 4F
看來用字串還是最快的orz
08/11 23:30, 4F

08/11 23:30, , 5F

08/11 23:38, , 6F
高手出現了! 話說那天去SYSOP朝聖時赫然發現T大的蹤跡
08/11 23:38, 6F

08/11 23:38, , 7F
才知道原來你是小組長XDDD
08/11 23:38, 7F

08/12 00:44, , 8F
用字串 replace只會取代一次喔!結果應該不符需求
08/12 00:44, 8F

08/12 18:20, , 9F
樓上 w3c建議第二個參數使用函數 因為可以傳進match到的
08/12 18:20, 9F

08/12 18:20, , 10F
值作判斷在丟出要取代的字
08/12 18:20, 10F
文章代碼(AID): #1COhSywp (Ajax)
討論串 (同標題文章)
文章代碼(AID): #1COhSywp (Ajax)