Is a url query parameter valid if it has no value?

前端 未结 8 1115
滥情空心
滥情空心 2020-11-28 05:41

Is a url like http://example.com/foo?bar valid?

I\'m looking for a link to something official that says one way or the other. A simple yes/no answer or

相关标签:
8条回答
  • 2020-11-28 05:56

    As all other answers described, it's perfectly valid for checking, specially for boolean kind stuff

    Here is a simple function to get the query string by name:

    function getParameterByName(name, url) {
        if (!url) {
            url = window.location.href;
        }
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    

    and now you want to check if the query string you are looking for exists or not, you may do a simple thing like:

    var exampleQueryString = (getParameterByName('exampleQueryString') != null);
    

    the exampleQueryString will be false if the function can't find the query string, otherwise will be true.

    0 讨论(0)
  • 2020-11-28 06:00

    It is valid: see Wikipedia, RFC 1738 (3.3. HTTP), RFC 3986 (3. Syntax Components).

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