【问题标题】:Extract and keep URLs of a domain from Javascript string从 Javascript 字符串中提取并保留域的 URL
【发布时间】:2021-08-19 02:30:10
【问题描述】:

我需要从 HTML 代码的 JS 字符串中提取属于 https://twitter.com 域的 URL,并将它们存储为变量数组。我知道我正在寻找 RegEx (https?:\/\/(.+?\.)?twitter\.com(\/[A-Za-z0-9\-\._~:\/\?#\[\]@!$&'\(\)\*\+,;\=]*)?)。我的问题是我不知道是什么命令在 JS 中找到了这个,虽然我已经找过了。

我的项目合作伙伴正在填充我在本地存储为 HTML 文件的 Google Sheets 表格,我在单独的 HTML 页面上获取该表格并将其推送到控制台,如下所示。我的最终目标是将他放在 JS 数组中的多个列中的 twitter 个人资料的链接供以后使用。

fetch('Directory.html').then(function (response) {
    return response.text();
}).then(function (html) {
    console.log(html);
}).catch(function (err) {
    console.warn('Ooga booga.', err);
});

感谢任何见解。我爱这个社区,祝福你们。

编辑

在下面的评论之后,我已经实现了这段代码,但 Chromium 控制台会打印整个文档,就好像它没有过滤任何内容一样。为什么是这样? 我最初尝试在正则表达式内容之前和之后没有正斜杠 / ,但 Chromium 控制台抱怨了一个意外的 : (冒号)令牌。这是为什么呢?

fetch('Directory.html').then(function (response) {
    // The API call was successful!
    return response.text();
}).then(function (html) {
    // This is the HTML from our response as a text string
    console.log(html);
}).catch(function (err) {
    // There was an error
//  console.warn('Something went wrong.', err);
});
const paragraph = html;
const regex = /(https?:\/\/(.+?\.)?twitter\.com(\/[A-Za-z0-9\-\._~:\/\?#\[\]@!$&'\(\)\*\+,;\=]*)?)/;
const found = paragraph.match(regex);

console.log(found);

【问题讨论】:

  • 您可以开始here但是:使用正则表达式来解析 HTML 或 JavaScript 是非常有问题的,并且通常不被接受。例如,您如何确定您匹配的字符串不在注释内或引用字符串内?您需要比 JavaScript 正则表达式提供的功能更强大的功能。
  • @Booboo 谢谢你的指导。我相信我会从这里处理它。在这种特定情况下,不会出现该问题,但为了将来参考,什么更适合?也许完全是另一种语言?
  • Here 是一些想法。

标签: javascript regex


【解决方案1】:

在这里展示我自己的作品。非常感谢@Booboo。

fetch('Directory.html').then(function (response) {

    return response.text();
}).then(function (html) {

const paragraph = html;
const regex = /(https?:\/\/(.+?\.)?twitter\.com(\/[A-Za-z0-9\-\._~:\/\?#\[\]@!$&'\(\)\*\+,;\=]*)?)/g;
const found = paragraph.match(regex);
console.log(found);
});

我使用了一个名为 csi.js 的库到 fetch 一个外部 HTML 文档。

const paragraph = html 可能是多余的一行。

const regex = 将“https://twitter.com/”标识为我想要的文本,并使用g 标志来获取字符串中的所有实例,而不仅仅是一个。

const found = 行在字符串中查找匹配项。

console.log 将结果打印到浏览器的控制台中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多