另一種方法:
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 :)');
來源
2010-06-16 17:09:37
CMS
它將無法正常工作,因爲替換隻會替換匹配的字符串的第一次出現。 – Matias 2010-06-16 17:10:13
只能替代每個笑臉的第一次出現。在一個像「這被替換:)但不是這個:)」的字符串中,第二個保持不變。 – Guffa 2010-06-16 17:12:38
還要確保在'for ... in'語句中使用'var',否則,如果代碼位於未在該範圍中聲明'smile'變量的函數內,它將變爲全局變量,並使用'如果(emoticons.hasOwnProperty(smile))'在循環內部是個好主意。 – CMS 2010-06-16 17:14:12