-1

I am trying to get just the YouTube embed url from an html embed string.

user puts in an embed-html string to an input. Then i want to strip it down to just the embed link, so i can always have them in my pre-made iframe.

let str = '<iframe width="560" height="315" src="https://www.youtube.com/embed/a24p_KjdpKE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';

let indexOfURL = str.indexOf('http');
let embedURL = str.slice(indexOfUrl, str.find(-the-next-double-speech-mark-after-indexOfUrl));

console.log(embedUrl);

Is there a cheeky regex that would do this for me?

Aid19801
  • 1,175
  • 1
  • 17
  • 30
  • 2
    Possible duplicate of [Regular expression for youtube links](https://stackoverflow.com/questions/3717115/regular-expression-for-youtube-links) – VLAZ Feb 01 '19 at 12:41
  • Although, I'm not sure why you need a regex. If you just get the value of `src`, that should work, right? – VLAZ Feb 01 '19 at 12:42
  • @VLAZ yeah that would work. But as it's in a string i need to say "find src, take from 5 chars after that... then stop at the *next* set of double speech marks. I suppose i could keep defining a new string. I feel like there's a JS jiggery pokery way of doing this though. – Aid19801 Feb 01 '19 at 12:44
  • [parse it as HTML](https://stackoverflow.com/questions/10585029/parse-an-html-string-with-js) then just literally go `element.src` to get the value of that attribute? – VLAZ Feb 01 '19 at 12:47

1 Answers1

0

Thanks to @VLAZ - i wasn't familiar with HTML parsing before. Not sure why. Anyway, a quick 5-min read on it got me to a point I'd written this, which solves my needs. I hope it solves yours too, if you're reading this. but if it doesn't, i dont overly care.

Note: it works for Vimeo, Soundcloud and YouTube (pasting in their html embed).

const changeEmbedHTMLIntoEmbeddableURL = html => {
            let parser = new DOMParser();
            let htmlDoc = parser.parseFromString(html, 'text/html');
            let embeddableURL = htmlDoc.getElementsByTagName('iframe')[0].src;
            console.log('Embeddable URL: ', embeddableURL);
            return embeddableURL;
}
Aid19801
  • 1,175
  • 1
  • 17
  • 30