【问题标题】:Reform and refine the regex of the URL改革和细化 URL 的正则表达式
【发布时间】:2018-04-22 21:24:26
【问题描述】:

我想用正则表达式分解网站的 URL。网址类似如下:

https://product.testing.com/intro/index.aspx?source=newsletter&product=watch&brand=rolex 

我使用的正则表达式如下:

(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?(product\.)(testing\.)(com\/)(.*)(\?|\?)([^=]\w+(?=&))

第一个问题是,我想把aspx后面的部分砍掉?分成几部分,即 source=newsletter、product=watch 等,并且代码在最后一部分不起作用,我做错了什么,应该如何更改?

第二个问题是,域名部分是一种硬编码...我怎样才能使它更好更灵活例如可以应用于https://contact.testing.com/contactoursales/index.aspx?

提前感谢您的帮助!

【问题讨论】:

  • 如果url不包含任何参数怎么办?

标签: javascript regex


【解决方案1】:

我建议使用 url 包,而不是正则表达式来解析 URL。

const URL = require('url');

const url = 'https://product.testing.com/intro/index.aspx?source=newsletter&product=watch&brand=rolex';

// Pass true to parse the querystring too
const parsed = URL.parse(url, true); 

将输出:

Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'product.testing.com',
  port: null,
  hostname: 'product.testing.com',
  hash: null,
  search: '?source=newsletter&product=watch&brand=rolex',
  query: { source: 'newsletter', product: 'watch', brand: 'rolex' },
  pathname: '/intro/index.aspx',
  path: '/intro/index.aspx?source=newsletter&product=watch&brand=rolex',
  href: 'https://product.testing.com/intro/index.aspx?source=newsletter&product=watch&brand=rolex' }

我想砍掉aspx之后的部分?成碎片,即 source=newsletter、product=watch 等,并且代码不适用于 最后一部分,我做错了什么,我应该如何改变?

true 作为第二个参数传递给url.parse 将为您解析查询字符串。

console.log(params.query);

/* {
    source: 'newsletter',
    product: 'watch',
    brand: 'rolex'
} */

如果你不使用 node.js,你可以使用 webpack 在浏览器上使用 url 包。

webpack url-parser.js -o url-parser.min.js

【讨论】:

  • 感谢 Marcos,解决方案很棒!但据我了解,它是 node.js 对吗?如果我想用javascript中最传统的方式来提取之前的代码一样的信息,我该怎么做呢?
  • 不客气。正如答案的最后一部分解释的那样,您可以在浏览器上使用它。该模块是用纯 Javascript 编写的,因此可以在浏览器上使用。您无需重新发明轮子。
  • @PakHangLeung 没有传统的方法,你应该解析 URL,或者你自己构建一个解析器,或者使用一个可以工作和记录的解析器,比如来自节点的 url 包。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多