正则表达式只替换整个单词

时间:2014-11-15 22:20:23

标签: javascript regex emoticons twitch

我试图修改一个名为ReChat的插件,因此它支持其他表情符号,而不是默认表情符号。

我需要使用正则表达式来替换整个单词我知道您需要添加\b元字符,但我无法使其正常工作。

例如,如果有两个名称为emotICONemotI的表情符号,它将始终显示emotI的图像。

这是装载程序:

ReChat.Playback.prototype._loadEmoticons = function() {
  var that = this;
  this._emoticons = [];
  ReChat.get('https://api.twitch.tv/kraken/chat/emoticons', {}, function(result) {
    $.each(result.emoticons, function(i, emoticon) {
      var image = emoticon.images[0];
      if (image.emoticon_set === 27) {
        that._emoticons.push({

          regex: new RegExp(emoticon.regex, 'g'),
          code: $('<span>').addClass('emoticon').css({ 'background-image': 'url(' + image.url + ')', 'height': image.height, 'width': image.width }).prop('outerHTML').replace(/&quot;/g, "'")
        });
      }
    });
  });
};

这是替换者​​:

ReChat.Playback.prototype._replaceEmoticons = function(text) {
    $.each(this._emoticons, function(i, emoticon) {

        text = text.replace(emoticon.regex, emoticon.code);

    });
    return text;
}

如果您需要完整的源代码,请访问https://github.com/pencil/rechat

1 个答案:

答案 0 :(得分:0)

嗯,您需要使用\b两次。所以它可能是这样的:

/\bword\b/

这是因为\b特殊字符用于边界,并且它与任何特定字符都不匹配。

您还可以使用匹配空格的\s

/\sword\s/