How to get the query string by javascript?

前端 未结 10 1564
深忆病人
深忆病人 2020-11-27 03:36

How to extract the query string from the URL in javascript?

Thank you!

10条回答
  •  -上瘾入骨i
    2020-11-27 04:13

    If you're referring to the URL in the address bar, then

    window.location.search
    

    will give you just the query string part. Note that this includes the question mark at the beginning.

    If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:

    url.substring(url.indexOf("?"))
    

    That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.

提交回复
热议问题