我有一个陣列:
emoticons = {
':-)' : 'smile1.gif',
':)' : 'smile2.gif',
':D' : 'smile3.gif'
}
然後我的文字有可變性。
var text = 'this is a simple test :)';
和帶有網站網址的變數
var url = "http://www.domain.com/";
如何編寫將符號替換為其圖像的函式?
<img>
標簽結果應為:
<img src="http://www.domain.com/simple2.gif" />
(我必须將var變數連線到圖片的名稱)。
非常感谢您!
最新回復
- 5月前1 #
- 5月前2 #
for ( smile in emoticons ) { text = text.replace(smile, '<img src="' + url + emoticons[smile] + '" />'); }
- 5月前3 #
使用帶有查詢替換元素陣列的正則表達式效果很好。
var emotes = [ [':\\\)', 'happy.png'], [':\\\(', 'sad.png'] ]; function applyEmotesFormat(body){ for(var i = 0; i < emotes.length; i++){ body = body.replace(new RegExp(emotes[i][0], 'gi'), '<img src="emotes/' + emotes[i][1] + '">'); } return body; }
另一種方法:
Edit: @ pepkin88提出了一个非常好的建議,根据
emoticons
的屬性名稱構建正則表達式 物件。這很容易做到,但是如果我们希望它能够正常工作,就必须轉義元字元。
轉義的模式儲存在陣列中,以後用於使用
RegExp
構建正則表達式 構造器,基本上將所有与|
分開的模式都加入 元字元。