Using location.search to locate a parameter's value

前端 未结 4 1558
走了就别回头了
走了就别回头了 2021-02-09 16:05

I’m working on a tool which takes the value parameters in the URL and does a few things with them.

My issue is, I can’t seem to use document.location to show the specifi

4条回答
  •  孤独总比滥情好
    2021-02-09 16:45

    location.search will return all after question mark including it. So there is universal js to get value of the first parameter (even if url has more parameters):

    var desire = location.search.slice(1).split("&")[0].split("=")[1]
    

    Example: let's take url http://example.com?name=jon&country=us

    1. location.search will be equal to ?name=jon&country=us
    2. .slice(1) skips the ?, returning the rest of the string.
    3. .split("&")[0] splits it into two strings (name=jon and country=us) and takes first one
    4. .split("=")[1] splits name=jon into name and jon and takes the second one. Done!

提交回复
热议问题