2010-06-16 11 views
14

我有一個數組:更換的表情列表與自己的形象

emoticons = { 
    ':-)' : 'smile1.gif', 
    ':)' : 'smile2.gif', 
    ':D' : 'smile3.gif'  
} 

然後我與文字variabile的。

var text = 'this is a simple test :)'; 

,並與網站

var url = "http://www.domain.com/"; 

的URL變量如何寫替換其圖像符號的功能?

<img>標籤的結果應該是:

<img src="http://www.domain.com/simple2.gif" /> 

(我來連接的URL varible到圖像的名稱)。

非常感謝!

回答

4
for (smile in emoticons) 
{ 
    text = text.replace(smile, '<img src="' + url + emoticons[smile] + '" />'); 
} 
+1

它將無法正常工作,因爲替換隻會替換匹配的字符串的第一次出現。 – Matias 2010-06-16 17:10:13

+0

只能替代每個笑臉的第一次出現。在一個像「這被替換:)但不是這個:)」的字符串中,第二個保持不變。 – Guffa 2010-06-16 17:12:38

+1

還要確保在'for ... in'語句中使用'var',否則,如果代碼位於未在該範圍中聲明'smile'變量的函數內,它將變爲全局變量,並使用'如果(emoticons.hasOwnProperty(smile))'在循環內部是個好主意。 – CMS 2010-06-16 17:14:12

33

另一種方法:

function replaceEmoticons(text) { 
    var emoticons = { 
    ':-)' : 'smile1.gif', 
    ':)' : 'smile2.gif', 
    ':D' : 'smile3.gif' 
    }, url = "http://www.domain.com/"; 
    // a simple regex to match the characters used in the emoticons 
    return text.replace(/[:\-)D]+/g, function (match) { 
    return typeof emoticons[match] != 'undefined' ? 
      '<img src="'+url+emoticons[match]+'"/>' : 
      match; 
    }); 
} 

replaceEmoticons('this is a simple test :)'); 
// "this is a simple test <img src="http://www.domain.com/smile2.gif"/>" 

編輯:@pepkin88取得一個很好的建議,建立一個基於該emoticons對象的屬性名稱的正則表達式。

它可以很容易地完成,但如果我們希望這能夠正常工作,我們必須轉義元字符。

轉義模式存儲在一個數組上,後來用於使用RegExp構造函數構建正則表達式,基本上連接了所有用|元字符分隔的模式。

function replaceEmoticons(text) { 
    var emoticons = { 
    ':-)' : 'smile1.gif', 
    ':)' : 'smile2.gif', 
    ':D' : 'smile3.gif', 
    ':-|' : 'smile4.gif' 
    }, url = "http://www.domain.com/", patterns = [], 
    metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g; 

    // build a regex pattern for each defined property 
    for (var i in emoticons) { 
    if (emoticons.hasOwnProperty(i)){ // escape metacharacters 
     patterns.push('('+i.replace(metachars, "\\$&")+')'); 
    } 
    } 

    // build the regular expression and replace 
    return text.replace(new RegExp(patterns.join('|'),'g'), function (match) { 
    return typeof emoticons[match] != 'undefined' ? 
      '<img src="'+url+emoticons[match]+'"/>' : 
      match; 
    }); 
} 

replaceEmoticons('this is a simple test :-) :-| :D :)'); 
+1

如果根據' emoticons'。 – pepkin88 2010-09-07 15:12:44

+1

@ pepkin88:很好的建議:),我添加了一個使得這成爲可能的功能。 – CMS 2010-09-07 20:39:08

+1

這可以通過關閉'replace()'進一步增強(類似於[這個答案](http://stackoverflow.com/questions/286921/javascript-efficiently-replace-all-accented-characters-in-a -string/614397#614397)...) - 這會加速重複調用該函數。 – Tomalak 2010-09-10 15:06:40

0

對查找替換元素的數組使用正則表達式效果很好。

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; 
}