【教程分享】JavaScript正则表达式:获取网页中所有URL链接

8 min read

好的,可以尝试以下代码:

// 获取页面中所有的url地址
const urls = [];
const pattern = /((http|https):\/\/[^\s]+)/g;

const pageContent = document.documentElement.innerHTML;
const matches = pageContent.match(pattern);

if (matches) {
  matches.forEach(match => {
    urls.push(match);
  });
}

console.log(urls);

以上代码会使用正则表达式在页面内容中提取出所有的 URL 地址,并存储在 urls 数组中。请注意,这仅适用于现代浏览器环境,如果在 Node.js 中运行,需要使用不同的代码来获取页面内容。