Javascript 子字符串/正则表达式获取保存在字符串中的 src 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12393671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
substring/regex to get a src value held in a string
提问by CLiown
I have a string with the value:
我有一个带有值的字符串:
var string = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>"
I'd like to take the URL
held in the src
attribute part of the string if possible.
如果可能,我想URL
保留在src
字符串的属性部分。
How can I do this using JavaScript?
我如何使用 JavaScript 做到这一点?
回答by driangle
One way to do it is to use regular expressions.
一种方法是使用正则表达式。
var str = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>";
var regex = /<img.*?src='(.*?)'/;
var src = regex.exec(str)[1];
console.log(src);
回答by Loktar
Alternative method if its always going to be html data.
如果它总是 html 数据的替代方法。
var string ="<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>";
var elem= document.createElement("div");
elem.innerHTML = string;
var images = elem.getElementsByTagName("img");
for(var i=0; i < images.length; i++){
console.log(images[i].src);
}
?
回答by David says reinstate Monica
One approach, is the following:
一种方法如下:
var string = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>",
srcWithQuotes = string.match(/src\=([^\s]*)\s/)[1],
src = srcWithQuotes.substring(1,srcWithQuotes.length - 1);
console.log(src);?
This effectively matches a sequence of characters starting with src=
(the =
is escaped with a back-slash because, otherwise, it holds special meaning within regular expressions), followed by a sequence of non-white-space characters (^\s*
) followed by a white-space character (\s
).
这有效地匹配以src=
(=
用反斜杠转义,因为否则它在正则表达式中具有特殊含义)开头的字符序列,后跟一系列非空白字符 ( ^\s*
) 后跟一个空白字符 ( \s
).
This expression explicitly captures the quotes used to delimit the src
attribute, the src
is returned by taking a substring of the srcWithQuotes
variable, starting at 1
(the first, the zeroeth, character should be the attribute delimiter) until the index before the last character (the final quote delimiting the attribute).
此表达式显式捕获用于分隔src
属性的引号,src
通过获取srcWithQuotes
变量的子字符串返回,从1
(第一个,第零个,字符应该是属性分隔符)开始,直到最后一个字符之前的索引(最后一个引号)定界属性)。
There is a slightly convoluted (but potentially more reliable) approach, using a document fragment:
使用文档片段有一种稍微复杂(但可能更可靠)的方法:
var string = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>",
temp = document.createElement('div'),
frag = document.createDocumentFragment();
temp.innerHTML = string;
frag.appendChild(temp);
console.log(temp.getElementsByTagName('img')[0].src);??????
Of course, in this example, you could use any approach you like to find the image within the temp
node (getElementById()
, getElementsByClassName()
...).
当然,在本例中,您可以使用任何您喜欢的方法在temp
节点 ( getElementById()
, getElementsByClassName()
...) 中查找图像。
回答by Paul S.
Native DOM (will result in GETs)
本机 DOM(将导致 GET)
var str = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>",
d = document.createElement('div'),
srcs = [];
d.innerHTML = str;
srcs = Array.prototype.slice.call(d.querySelectorAll('[src]'),0);
while( srcs.length > 0 ) console.log( srcs[0].src ), srcs.shift();
or RegExp
或正则表达式
var str = "<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>",
re = /\ssrc=(?:(?:'([^']*)')|(?:"([^"]*)")|([^\s]*))/i, // match src='a' OR src="a" OR src=a
res = str.match(re),
src = res[1]||res[2]||res[3]; // get the one that matched
src; // http://api.com/images/UID
回答by Arthur Padilha
Assuming that you want to match specifically the src
property in an <img>
tag.
You can use this Regex because it will match the tag, still preserve other properties it might have and also other content inside the src
property:
假设您要专门匹配标签中的src
属性<img>
。您可以使用此正则表达式,因为它将匹配标签,仍然保留它可能具有的其他属性以及src
属性中的其他内容:
var matches = string.match(/<img([^>]+)src="[/]?([^"]+)"([^>]*)>|<( *)img( *)[/>|>]/g);
var matches = string.match(/<img([^>]+)src="[/]?([^"]+)"([^>]*)>|<( *)img( *)[/>|>]/g);
it can be improved but works fine with some varieties of typing.
它可以改进,但适用于某些类型的打字。
for example, if you want to match <img>
or even <img src="/200px-Unofficial_JavaScript_logo_2.svg.png" alt="" width="100" height="172" />
to add something to the url, you can do the following replacement:
例如,如果您想匹配<img>
甚至<img src="/200px-Unofficial_JavaScript_logo_2.svg.png" alt="" width="100" height="172" />
向 url 添加一些内容,您可以执行以下替换:
string.replace(/<img([^>]+)src="[/]?([^"]+)"([^>]*)>|<( *)img( *)[/>|>]/g, '<img $1src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Unofficial_JavaScript_logo_2.svg/$2" $3>');
string.replace(/<img([^>]+)src="[/]?([^"]+)"([^>]*)>|<( *)img( *)[/>|>]/g, '<img $1src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Unofficial_JavaScript_logo_2.svg/$2" $3>');
回答by steve ryu
You can use jQuery to do this, using the find method, get the src attribute of the image.
您可以使用 jQuery 来执行此操作,使用 find 方法,获取图像的 src 属性。
var str = '<img src="/uploads/thumbnail/79a23278ec18b2fc505b06ab799d5ec672094e79.jpg">';
var result = $(str).find('img').eq(0).attr('src'); // get a image src
回答by biojazzard
Faccy 2015: Using jQuery and CofeeScript via DOM
Faccy 2015:通过 DOM 使用 jQuery 和 CofeeScript
str = '<img alt='' src='http://api.com/images/UID' /><br/>Some plain text<br/><a href='http://www.google.com'>http://www.google.com</a>'
img = $(@.content).find('img').each ()->
srcimg = $(@).attr('src')
console.log srcimg