[英]Extract SRC from a iFrame in Javascript
I have an iframe in a string, as below:我在一个字符串中有一个 iframe,如下所示:
let data = "<iframe src=\"https://example.com/3380098/test/embed\" height=\"500\" width=\"100%\" style=\"border:0\"></iframe>"
My goal is to extract the number '3380098'
from the src.我的目标是从 src 中提取数字
'3380098'
。
And I am stuck with parsing it.我坚持解析它。
Here is my approach:这是我的方法:
var parser = new DOMParser();
var parsedIframe = parser.parseFromString(data, "text/html");
let iFrame = parsedIframe.getElementsByTagName("iframe");
But from here on, I am unable to get the src of the iframe.但是从这里开始,我无法获得 iframe 的 src。 Please help.
请帮忙。
This question is different because there is no real iframe, it's a string.这个问题不同,因为没有真正的 iframe,它是一个字符串。
Do you really need to parse it as DOM?你真的需要将它解析为 DOM 吗? If it's always going to be in a similar format with a similar URL then you can do some regex instead, like:
如果它总是采用类似的格式和类似的 URL,那么你可以做一些正则表达式,比如:
let data = "<iframe src=\"https://example.com/3380098/test/embed\" height=\"500\" width=\"100%\" style=\"border:0\"></iframe>";
let match = data.match(/example\.com\/([0-9]+)\//i);
alert(match[1]);
Just read the src
property of the first element in collection, then parse the URL.只需读取集合中第一个元素的
src
属性,然后解析 URL。
let data = "<iframe src=\\"https://example.com/3380098/test/embed\\" height=\\"500\\" width=\\"100%\\" style=\\"border:0\\"></iframe>"; var parser = new DOMParser(); var parsedIframe = parser.parseFromString(data, "text/html"); let iFrame = parsedIframe.getElementsByTagName("iframe"); // Read URL: let src = iFrame[0].src; console.log(src); // Parse URL: let match = src.match(/\\/(\\d+)\\//); let digits = match ? match[1] : null; console.log(digits);
parsedIframe.getAttribute("src")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.