Get path and query string from URL using javascript

后端 未结 5 1251
失恋的感觉
失恋的感觉 2020-12-08 06:08

I have this:

http://127.0.0.1:8000/found-locations/?state=--&km=km

I want this:

found-locations/?state=--&km=km
<         


        
相关标签:
5条回答
  • 2020-12-08 06:31
    window.location.pathname + window.location.search
    

    Will get you the base url /found-locations plus the query string ?state=--&km=km

    0 讨论(0)
  • 2020-12-08 06:32

    Use location.pathname and location.search:

    (location.pathname+location.search).substr(1)
    
    0 讨论(0)
  • 2020-12-08 06:32

    get all path, query and even hash: location.href.replace(location.origin, '')

    0 讨论(0)
  • 2020-12-08 06:40

    If your url is a string, you can create URL object and use pathname and search property.

     let strurl = 'http://www.test.com/param1/param2?test=abc';
     let url = new URL(strurl)
     let pathandQuery = url.pathname + url.search;
    

    let strurl = 'http://www.test.com/param1/param2?test=abc';
    let url = new URL(strurl)
    let pathandQuery = url.pathname + url.search;
    
    console.log(pathandQuery);

    0 讨论(0)
  • 2020-12-08 06:48

    URI.js is a nice JavaScript library for parsing URIs. It can do what you requested with a nice fluent syntax.

    0 讨论(0)
提交回复
热议问题