Regex to get first word after slash in URL

后端 未结 7 2177
孤街浪徒
孤街浪徒 2020-12-08 21:32

I need to get the first word after slash in a url in javascript, I assume using a regex would be ideal.

Here\'s an idea of what the URLs can possibly look like :

相关标签:
7条回答
  • 2020-12-08 21:53

    Here is the quick way to get that in javascript

    var urlPath = window.location.pathname.split("/");
    if (urlPath.length > 1) {
      var first_part = urlPath[1];
      alert(first_part); 
    }
    
    0 讨论(0)
  • 2020-12-08 21:55

    Non-regex.

    var link = document.location.href.split('/');
    alert(link[3]);
    
    0 讨论(0)
  • 2020-12-08 22:02

    Try with:

    var url = 'http://mysite.com/section-with-dashes/';
    var section = url.match(/^http[s]?:\/\/.*?\/([a-zA-Z-_]+).*$/)[0];
    
    0 讨论(0)
  • 2020-12-08 22:06
    $url = 'http://mysite.com/section/subsection';
    
    $path = parse_url($url, PHP_URL_PATH);
    
    $components = explode('/', $path);
    
    $first_part = $components[0];
    
    0 讨论(0)
  • 2020-12-08 22:09

    Exploding an url in javascript can be done using the official rfc2396 regex:

    var url = "http://www.domain.com/path/to/something?query#fragment";
    var exp = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
    

    This will gives you:

    ["", "http:", "http", "//www.domain.com", "www.domain.com", "/path/to/something", "?query", "query", "#fragment", "fragment", ""]
    

    Where you can, in your case, easily retrieve you path with:

    var firstPortion = exp[5].split("/")[1]
    
    0 讨论(0)
  • 2020-12-08 22:15

    JavaScript with RegEx. This will match anything after the first / until we encounter another /.

    window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');
    
    0 讨论(0)
提交回复
热议问题