gpt4 book ai didi

javascript - 用图片替换表情符号列表

转载 作者:可可西里 更新时间:2023-11-01 01:36:27 25 4
gpt4 key购买 nike

我有一个数组:

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

然后我有一个带有文本的变量。

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

和一个带有网站 url 的变量

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

如何编写用图像替换符号的函数?

<img>标签结果应该是:

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

(我必须将 url 变量连接到图像名称)。

非常感谢!

最佳答案

另一种方法:

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 :)');

关于javascript - 用图片替换表情符号列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3055515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com