替换正则表达式中的 img 元素 src 属性
解决了它,以防有人需要它在这里
var feed = feeds.entries[i].content; var parsedFeed = feed.replace(/src=/gi, "tempsrc="); var tmpHolder = document.createElement('div'); tmpHolder.innerHTML=parsedFeed;
我有一个包含 html 标记的字符串,其中包括
我想对字符串运行正则表达式,将每个 src attr 替换为 tmpSrc,
这样
<img src='path.jpg'/>
将变成,
<img tmpSrc='path.jpg'/>
顺便说一下,这是在 javascript 中
,这是在其他地方发布的根本问题,但尚未解决已解决
谢谢
Solved it in case anyone needs it here it is
var feed = feeds.entries[i].content; var parsedFeed = feed.replace(/src=/gi, "tempsrc="); var tmpHolder = document.createElement('div'); tmpHolder.innerHTML=parsedFeed;
I have a string containing html markup which include <img src='path.jpg'/>
I would like to run a regex against the string to replace every src attr to tmpSrc
so
<img src='path.jpg'/>
would turn into
<img tmpSrc='path.jpg'/>
this is in javascript by the way
and here is the root issue posted in other places but has not been solved
Browser parse HTML for jQuery without loading resources
How to parse AJAX response without loading resources?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果这是您控制的字符串,而不是从网页检索的 HTML,那么您确实可以安全地使用正则表达式。要将所有出现的
更改为
,您可以使用以下操作:
其他发帖者所说的是正则表达式不好用于从网页检索的 HTML,因为不同的浏览器返回不同形式的 HTML,因此很难可靠地匹配它。但是,如果您尝试替换的字符串在您自己的控制之下并且您可以知道它的格式,那么这个正则表达式应该可以正常工作。
If this is a string you control and not HTML retrieved from a web page, then you can indeed safely use a regex. To change all occurences of
<img src=
to<img tmpSrc=
, you can use this operation:What the other posters have been saying is that regex are not good to use on HTML retrieved from a web page because different browsers return different forms of HTML so it makes it hard to reliably match it. But, if the string you're trying to do a replace on is under your own control and you can know the format of it, then this regex should work fine.
使用 RegExp 操作 HTML 很容易出错。
如果您可以忍受在页面中包含 jQuery:
Manipulating HTML with RegExps is error prone.
If you can suffer to include jQuery in your page:
作为字符串:
使用 DOM:
as string:
using DOM:
查看这篇 帖子,解释使用正则表达式的问题解析 HTML。这很棘手,而且可能不值得付出努力。我认为没有任何方法可以保证有效。
Check out this post explaining the problems with using regexes to parse HTML. It is tricky and probably not worth the effort. I don't think there is any way that is guaranteed to work.