Dam*_*ano 14 javascript emoticons
我有一个数组:
emoticons = {
':-)' : 'smile1.gif',
':)' : 'smile2.gif',
':D' : 'smile3.gif'
}
Run Code Online (Sandbox Code Playgroud)
然后我对文本有一个变化.
var text = 'this is a simple test :)';
Run Code Online (Sandbox Code Playgroud)
和一个带有网站网址的变量
var url = "http://www.domain.com/";
Run Code Online (Sandbox Code Playgroud)
如何编写一个用符号替换符号的函数?
该<img>
标签的结果应该是:
<img src="http://www.domain.com/simple2.gif" />
Run Code Online (Sandbox Code Playgroud)
(我必须将url varible连接到图像的名称).
非常感谢你!
CMS*_*CMS 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"/>"
Run Code Online (Sandbox Code Playgroud)
编辑: @ 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 :)');
Run Code Online (Sandbox Code Playgroud)
for ( smile in emoticons )
{
text = text.replace(smile, '<img src="' + url + emoticons[smile] + '" />');
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16695 次 |
最近记录: |