Javascript 有没有办法从这个字符串中只获取URL?

Javascript 有没有办法从这个字符串中只获取URL?,javascript,regex,string,Javascript,Regex,String,我有这个字符串,我需要从中提取url <figure class="media"><oembed url="https://www.youtube.com/watch?v=P******"></oembed></figure> 您可以使用获取值 var str=`; console.log(str.match(/url=\“*?\”/)。在可用的地方使用适当的HTML解析器,而不是regexp const source=''; const d

我有这个字符串,我需要从中提取url

<figure class="media"><oembed url="https://www.youtube.com/watch?v=P******"></oembed></figure>
您可以使用获取值

var str=`;
console.log(str.match(/url=\“*?\”/)
。在可用的地方使用适当的HTML解析器,而不是regexp

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

log(oembed.getAttribute('url')这非常简单

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

您可以通过正则表达式使用匹配操作来匹配URL

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******
const字符串=`
`
常量匹配=string.match(/\bhtps?:\/\/.+(?=”)/gi)
// ["https://www.youtube.com/watch?v=P******"]
log({url:matches[0]})
// https://www.youtube.com/watch?v=P******
让str1='';
设urleindex=str1.indexOf(“url=”);
让extractUrl=str1.substring(urleindex+5,str1.indexOf(“>”,urleindex));

这适用于手头的特定示例,但是正则表达式中的
*
默认情况下是贪婪的,如果字符串后面有另一个
,它将一直匹配到该字符串。这可能需要添加惰性(非贪婪)
修饰符:
str.match(/url=\“*?\”/)
注意,OP说的是”我有这个字符串”,而不是“我的HTML文档中有这个”“。虽然此代码可能提供问题的解决方案,但最好添加有关其工作原因/方式的上下文。这可以帮助未来的用户学习,并将这些知识应用到他们自己的代码中。在解释代码时,用户可能会以投票的形式向您提供正面反馈。
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******
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));