How to check if a query string value is present via JavaScript?

后端 未结 10 1923
眼角桃花
眼角桃花 2021-01-30 00:25

How can I check if the query string contains a q= in it using JavaScript or jQuery?

10条回答
  •  长发绾君心
    2021-01-30 01:15

    In modern browsers, this has become a lot easier, thanks to the URLSearchParams interface. This defines a host of utility methods to work with the query string of a URL.

    Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m, you can grab the query string using window.location.search:

    const queryString = window.location.search;
    console.log(queryString);
    // ?product=shirt&color=blue&newuser&size=m
    

    You can then parse the query string’s parameters using URLSearchParams:

    const urlParams = new URLSearchParams(queryString);
    

    Then you can call any of its methods on the result.

    For example, URLSearchParams.get() will return the first value associated with the given search parameter:

    const product = urlParams.get('product')
    console.log(product);
    // shirt
    
    const color = urlParams.get('color')
    console.log(color);
    // blue
    
    const newUser = urlParams.get('newuser')
    console.log(newUser);
    // empty string
    

    You can use URLSearchParams.has() to check whether a certain parameter exists:

    console.log(urlParams.has('product'));
    // true
    
    console.log(urlParams.has('paymentmethod'));
    // false
    

    For further reading please click here.

提交回复
热议问题