How to parse a URL?

前端 未结 6 618

If there is one thing I just cant get my head around, it\'s regex.

So after a lot of searching I finally found this one that suits my needs:

function         


        
6条回答
  •  我在风中等你
    2020-11-27 03:46

    You just need to modify your regex a bit. For example:

    var aaaa="http://www.somesite.se/blah/sdgsdgsdgs";
    var m = aaaa.match(/^[^:]*:\/\/([^\/]+)(\/.*)$/);
    

    m will then contain the following parts:

    ["http://www.somesite.se/blah/sdgsdgsdgs", "www.somesite.se", "/blah/sdgsdgsdgs"]
    

    Here is the same example, but modified so that it will split out the "www." part. I think the regular expression should be written so that the match will work whether or not you you have the "www." part. So check this out:

    var aaaa="http://www.somesite.se/blah/sdgsdgsdgs";
    var m = aaaa.match(/^[^:]*:\/\/(www\.)?([^\/]+)(\/.*)$/);
    

    m will then contain the following parts:

    ["http://www.somesite.se/blah/sdgsdgsdgs", "www.", "somesite.se", "/blah/sdgsdgsdgs"]
    

    Now check out the same regular expression but with a url that does not start with "www.":

    var bbbb="http://somesite.se/blah/sdgsdgsdgs";
    var m = .match(/^[^:]*:\/\/(www\.)?([^\/]+)(\/.*)$/);
    

    Now your match looks like this:

    ["http://somesite.se/blah/sdgsdgsdgs", undefined, "somesite.se", "/blah/sdgsdgsdgs"]
    

    So as you can see it will do the right thing in both cases.

提交回复
热议问题