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

Javascript use the replace matched substring in a array key

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

Var emotesurl = {Emotename: 'URL'};

选项1是我要替换的句子 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 中不起作用,因为它 returns 未定义。我有点不知道如何解决这个问题。

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

看起来你想要 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);