-1

I have this string i need to extract the url from this.

<figure class="media"><oembed url="https://www.youtube.com/watch?v=P******"></oembed></figure>

I need to get output like this

url= https://www.youtube.com/watch?v=P******

5 Answers5

3

Beware Zalgo. Use a proper HTML parser where available, instead of regexp.

const source = '<figure class="media"><oembed url="https://www.youtube.com/watch?v=P******"></oembed></figure>';

const div = document.createElement('div');
div.innerHTML = source;

const oembed = div.querySelector('oembed');
console.log(oembed.getAttribute('url'));
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

You can use regular expression to fetch the value.

var str = `<figure class="media"><oembed url="https://www.youtube.com/watch?v=P******"></oembed></figure>`;

console.log(str.match(/url=\".*?\"/))
Akash Shrivastava
  • 1,365
  • 8
  • 16
  • 1
    This works for the specific example at hand, but the `*` in the regex is **greedy** by default, if there is another `"` later in the string, it will match all the way to that. This should probably have the lazy (non-greedy) `?` modifier added: `str.match(/url=\".*?\"/)` – cschatz Feb 21 '20 at 06:54
0

This is pretty straightforward

    let url = document.querySelector('figure.media oembed').getAttribute('url');
    console.log(url);
    // gives: https://www.youtube.com/watch?v=P******
0

You can match URL using match operation through regex

const string = `<figure class="media">
                 <oembed url="https://www.youtube.com/watch?v=P******"></oembed>
               </figure>`

const matches = string.match(/\bhttps?:\/\/.+(?=")/gi)
// ["https://www.youtube.com/watch?v=P******"]

console.log({ url: matches[0] })
// https://www.youtube.com/watch?v=P******
Ashok
  • 2,846
  • 1
  • 12
  • 20
0
let str1 = '<figure class="media"><oembed url="https://www.youtube.com/watch?v=P******"></oembed></figure>';
let urlIndex = str1.indexOf("url=");
let extractUrl = str1.substring(urlIndex + 5, str1.indexOf('">', urlIndex));
  • 1
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Feb 21 '20 at 07:36