admin管理员组文章数量:1322376
I have an image tag with a src and I want to prepend a website url onto the src but only if it doesn't start with http://. so far I have
content.replace(/(<img *src=")(.*?)"/, '$1' + this.websiteUrl + '$2"');
but I don't know how to do the not starting with http:// bit
I have an image tag with a src and I want to prepend a website url onto the src but only if it doesn't start with http://. so far I have
content.replace(/(<img *src=")(.*?)"/, '$1' + this.websiteUrl + '$2"');
but I don't know how to do the not starting with http:// bit
Share Improve this question asked Nov 26, 2012 at 9:53 PetePete 58.5k29 gold badges130 silver badges184 bronze badges4 Answers
Reset to default 5Use a negative lookahead:
content.replace(/(<img *src=")(?!http:\/\/)(.*?)"/, '$1' + this.websiteUrl + '$2"');
@Guffa's pattern is the answer. Just a couple of side-notes: suppose the markup looks like this <img alt="foo" src="foo/bar.png" />
, your pattern won't work, try this:
content.replace(/(<img.+src=")(?!http:\/\/)(.*?)"/,'$1' + this.websiteUrl + '$2"');
And if you're going to use this regex for an entire DOM(fragment), consider using a parser instead of regex, too. Here's a X-browser example
You don't really need a regex if you're just prepending some text. How about just:
if /^http:\/\//.test(img.src)
img.src = this.websiteUrl + img.src;
Where img
is the element you are changing the src attribute for.
If you don't have the img tag or one of it's parents as an object, but your HTML is well formed, you can use a DOMParser
to get them:
var parser = new DOMParser();
var doc = parser.parseFromString(html, "text/XML");
var collection = doc.getElementsByTagName("img");
for (var i = 0; i < collection.length, i++){
if /^http:\/\//.test(collection[i].src)
collection[i].src = this.websiteUrl + collection[i].src;
}
In my case the solution provided by Elias Van Ootegem didn't work. I'm using:
content.replace(/(<img[^]+?src=")(?!http:\/\/)(.*?)"/gi,'$1' + this.websiteUrl + '$2"');
This one works even if the img tag spread on 2 lines and even with multiple img tags
本文标签: Javascript Regex replacing src contentStack Overflow
版权声明:本文标题:Javascript Regex replacing src content - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742109172a2421165.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论