简体   繁体   中英

Extract SRC from a iFrame in Javascript

I have an iframe in a string, as below:

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.

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. Please help.

This question is different because there is no real iframe, it's a string.

Do you really need to parse it as DOM? If it's always going to be in a similar format with a similar URL then you can do some regex instead, like:

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.

 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM