用于在Javascript中获取URL组件的正则表达式

sin*_*pop -3 javascript regex

我一直很难使用正则表达式,但我认为现在我有合法的需求,而且我不确定是否可以使用它们来实现它.

我想要一个正则表达式,在执行时,返回给定URL的所有组件.它不是用于验证格式:前提条件是传递正确的URL(通常是它location.href).

期望的组件是:

  • 方案
  • 域
  • 端口(可选)
  • 路径
  • 请求参数

奖金:

  • 单独查询字符串参数
  • 分段
  • 用户密码

例子:

/regex/.exec('http://www.stackoverflow.com/questions/1/regex-for-getting-url-components-in-javascript') --> ["http://stackoverflow.com/questions/30868359/regex-for-getting-url-components-in-javascript", "http", "www.stackoverflow.com", undefined, "questions/30868359/regex-for-getting-url-components-in-javascript"]

/regex/.exec('https://localhost:8080/?a=1&b=2') --> ["http://www.stackoverflow.com/questions/1/regex-for-getting-url-components-in-javascript", "https", "localhost", "8080", "", "a=1&b=2"]


编辑:

为了澄清,我需要的是一个小代码,它创建一个代表URl的对象.然后我必须能够修改参数,模式等组件,并再次将结果作为字符串.AFAIK,我不能用本地位置对象做这个,但我一定是错的.

代码的大小必须特别小,因为它必须在页面的标题中同步加载.它最终可能会被复制到每个页面而不是作为外部文件包含在内.所以,起初,我更喜欢不依赖外部依赖.

epa*_*llo 5

获得没有正则表达式的部件的基本思路.

function parseUrl(url) {
  var a = document.createElement("a");
  a.href = url;

  var obj = {};
  var parts = ['protocol', 'hostname', 'host', 'pathname', 'port', 'search', 'hash', 'href'];

  parts.forEach(function(val) {
    obj[val] = a[val]
  });

  return obj;

}

console.log(parseUrl("http://localhost:8080/foo?bar=1"));
console.log(parseUrl("http://www.example.com#test"));
Run Code Online (Sandbox Code Playgroud)

根据您的编辑,您始终可以创建一个对象并覆盖toString()方法以输出更改.(下面可能不完美,写得很快)

    function parseUrl(url) {
      var a = document.createElement("a");
      a.href = url;

      function URL() {} 
      var obj = new URL();
      var parts = ['protocol', 'hostname', 'host', 'pathname', 'port', 'search', 'hash', 'href'];

      parts.forEach(function(val) {
        obj[val] = a[val]
      });
      
      URL.prototype.toString = function () {  
         var  out = this.protocol + "//" + this.host + this.pathname + this.search + this.hash;
          return out;
      
      }

      return obj;

    }

    var xxx = parseUrl("http://localhost:8080/foo?bar=1");
    xxx.hash = "#newHash";
    xxx.search = "?boom=new";
    console.log(xxx.toString());
Run Code Online (Sandbox Code Playgroud)