javascript - HTML:用图像替换文本微笑

标签 javascript html regex dom

假设有这两个字符串:

  • Test message :/
  • This too <a href="http://example.com">Example.com</a> :/

现在我用这样的图像替换微笑:

var message = 'Test message :/';
console.log(message.replace(/:\//ig, '<img src="smile1.png" alt=":/">'));

var message2 = 'This too: <a href="http://example.com">http://example.com</a> :/';
console.log(message2.replace(/:\//ig, '<img src="smile1.png" alt=":/">'));

我如何更改正则表达式,让它只替换像 :/ 这样的字符串HTML 标签之外?

最佳答案

在这个简单的例子中,先行断言就可以了:

message2 = 'smile :/  <a href="http://example.com">Example.com</a> :/ <img alt=":/"> and :/'
message2.replace(/:\/(?=[^<>]*(<|$))/g, "FOO")
> "smile FOO  <a href="http://example.com">Example.com</a> FOO <img alt=":/"> and FOO"

但总的来说,结构化方法对于 html 来说效果更好。遍历 DOM 树,找到文本节点并在那里进行简单的字符串替换。

对于那些想知道的人来说,这个正则表达式意味着

/
    :\/           a smile
    (?=           followed by
        [^<>]*    some chars but not < or >
        (         and then
            <|$   < or the end of input
        )
    )
/

要处理像 http:// 这样的事情,请再添加一次前瞻,这次是负数:“后面不跟斜杠”:

message2 = 'This too: <a href="http://example.com">http://example.com</a> :/';
message2.replace(/:\/(?=[^<>]*(<|$))(?!\/)/g, "FOO")
> "This too: <a href="http://example.com">http://example.com</a> FOO"

但我再说一遍:在处理 html 时,正则表达式不是您选择的工具。

关于javascript - HTML:用图像替换文本微笑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19823387/

相关文章:

javascript - 单独的 js 文件中的 getElementById 找不到 ASP.net 控件

javascript - 我想在 Jquery 中的图像上使用 onload 函数

html - 如何让两条文本并排放置并响应屏幕宽度的变化?

php - 根据 php echo 值更改 td bg 颜色

javascript - Jquery/Regex 不适用于 val/var?

python - 使用 python re.compile 和 beautiful soup 来匹配字符串

regex - 在powershell中获取文件名中正则表达式的索引

javascript - 使用 Typescript 在 Opaque 上区分联合

html - 图像剪裁父元素的边界半径? (苹果浏览器)

javascript - 试图让我的形象淡出工作