作者TonyQ (沉默是金。)
看板Ajax
標題Re: [問題] javascript replace的正規表達式
時間Wed Aug 11 22:44:09 2010
※ 引述《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
1F:推 megaman1206:不過經過實驗看起來用function反而會造成overhead 08/11 23:18
3F:→ TonyQ:基本上這種問題是不是有需要去作最佳化是by case 的 :~ 08/11 23:19
4F:推 megaman1206:看來用字串還是最快的orz 08/11 23:30
6F:推 s25g5d4:高手出現了! 話說那天去SYSOP朝聖時赫然發現T大的蹤跡 08/11 23:38
7F:→ s25g5d4:才知道原來你是小組長XDDD 08/11 23:38
8F:→ grence:用字串 replace只會取代一次喔!結果應該不符需求 08/12 00:44
9F:推 s25g5d4:樓上 w3c建議第二個參數使用函數 因為可以傳進match到的 08/12 18:20
10F:→ s25g5d4:值作判斷在丟出要取代的字 08/12 18:20