除非在某组文本中,否则替换字符串中的表情符号

时间:2013-01-14 23:52:34

标签: javascript regex

我试图用图片标记替换给定字符串中的表情符号,只要它不在某个字符组中。

假设:

var reg = /(?!<):\/(?![^<>]*>)/g,
    string = ':/ <a href="http://blah.com">http://blah.com</a> :/',
    result = string.replace(reg, 'IMG');

结果:IMG <a href="http://blah.com">httpIMG/blah.com</a> IMG

我想知道是否有办法忽略HTML标记中的替换,而不是仅仅在<>内。

3 个答案:

答案 0 :(得分:1)

也许这不是最好的解决方案,但如果您使用jQuery,以下“oneliner”可以完成这项工作:

var str = ":/ <a href='http://blah.com'>http://blah.com</a> :/";

$("<div />", { html : str }).contents().each(function() {
    if (this.nodeType === 3)
        this.nodeValue = this.nodeValue.replace(/:\//g, "IMG");
}).end().html();

DEMO: http://jsfiddle.net/Hfnje/

答案 1 :(得分:0)

为什么不将它与字边界相匹配?

/\B:\/\B/

匹配:
:/
foo:/ bar

但不是:
HTTP://
FOO:/酒吧

答案 2 :(得分:0)

在@VisioN的帮助下,我设法得到了这个:

message =
  $('<div />', html: message).contents().each(->
    if @nodeType is 3
      for replacement, emoticons of self.emoticons
        for emoticon in emoticons
          @nodeValue = @nodeValue.replace new RegExp(emoticon, 'g'),
            $('<span />', class:'emoticon ' + replacement, title: emoticon)[0].outerHTML

      $(@).replaceWith @nodeValue
  ).end().html()

它不漂亮,但它正在发挥作用。