-2

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.

asanas
  • 3,212
  • 8
  • 34
  • 61
  • Just access its `src` attribute? – CertainPerformance Dec 22 '18 at 04:20
  • Possible duplicate of [Get current URL from IFRAME](https://stackoverflow.com/questions/938180/get-current-url-from-iframe) – ic3b3rg Dec 22 '18 at 04:21
  • Just accessing src (like iFrame.src) gives me nothing. I also tried iFrame[0].src. But doesn't help. – asanas Dec 22 '18 at 04:23
  • @ic3b3rg that's not exactly the same thing - the src value could differ from the href of the page if the src value goes through a redirect first – Matthew Herbst Dec 22 '18 at 04:25
  • @MatthewHerbst OP reports `src` is always undefined - likely reason is the src is a different domain – ic3b3rg Dec 22 '18 at 04:31
  • @asanas I said the `src` *attribute*, not the `src` property, they're sometimes different (such as in this case). Select the created element, then `element.getAttribute('src')`, then you can play with it – CertainPerformance Dec 22 '18 at 04:50

3 Answers3

2

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]);
Jason Byrne
  • 1,339
  • 8
  • 18
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);
Alexander O'Mara
  • 56,044
  • 17
  • 157
  • 163
0
parsedIframe.getAttribute("src")
last_fix
  • 329
  • 4
  • 18