Javascript使用数组键中的替换匹配子字符串

时间:2015-01-09 12:13:41

标签: javascript regex replace

我试图将句子中的单词替换为表情符号。这些表情符号存储如下:

Var emotesurl = {Emotename: 'URL'};

option1是我要替换的句子 emoteregex是我的正则表达式

我的尝试:

var option1 = 'I am cool DatSheffy';
var emoteregex = new RegExp("(Volcania|DatSheffy)","g");
var emotesurl = {DatSheffy:"https://static-cdn.jtvnw.net/jtv_user_pictures/chansub-global-emoticon-bf13a0595ecf649c-24x30.png"};
option1.replace(emoteregex, emotesurl['DatSheffy']);   This returns url! YAY
option1.replace(emoteregex, "$&");   This returns DatSheffy

所以我认为可能是这样的:

option1.replace(emoteregex, emotesurl['$&']);  

这显然在javascript中不起作用,因为它返回undefined。我有点无能为力如何解决这个问题。

因此,此脚本部分的最终目标是将正则表达式中的单词DatSheffy或任何其他单词替换为该特定表情图像的URL。阵列中的Keyname与匹配的正则表达式相同。

1 个答案:

答案 0 :(得分:0)

看起来你想要replace的回调实现:



var emotesurl = {'brown': 'URL', 'xxx': 'foo'}; 

var option1 = "how now [brown] cow [xxx] [z]";
    
option1 = option1.replace(/\[(.*?)\]/gi, function(a, b) {
    // a is '[brown]' b is 'brown' - return emotesurl value or current as default
    return emotesurl[b] || a;
});

alert(option1);




相关问题