看板 Ajax 關於我們 聯絡資訊
※ 引述《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
megaman1206:不過經過實驗看起來用function反而會造成overhead 08/11 23:18
megaman1206:http://jsfiddle.net/mCMDZ/ 08/11 23:18
TonyQ:基本上這種問題是不是有需要去作最佳化是by case 的 :~ 08/11 23:19
megaman1206:看來用字串還是最快的orz 08/11 23:30
megaman1206:http://jsfiddle.net/mCMDZ/1/ 08/11 23:30
s25g5d4:高手出現了! 話說那天去SYSOP朝聖時赫然發現T大的蹤跡 08/11 23:38
s25g5d4:才知道原來你是小組長XDDD 08/11 23:38
grence:用字串 replace只會取代一次喔!結果應該不符需求 08/12 00:44
s25g5d4:樓上 w3c建議第二個參數使用函數 因為可以傳進match到的 08/12 18:20
s25g5d4:值作判斷在丟出要取代的字 08/12 18:20