假设有这两个字符串:
-
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/