How to add a parameter to the URL?

后端 未结 9 1018
遇见更好的自我
遇见更好的自我 2020-11-30 06:37

My current URL is: http://something.com/mobiles.php?brand=samsung

Now when a user clicks on a minimum price filter (say 300), I want my URL to become

9条回答
  •  臣服心动
    2020-11-30 07:39

    Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:

    
    
    add priceMin=300
    

    There is no need to check for ? as this is already the search part and you only need to add the param.

    If you don't want to even make use of a function you can write as so:

    add priceMin=300
    

    Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.

    Edit:

    In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:

    • if the parameter already exists, it should be changed.
    • if the parameter already exists multiple times, only the changed copy should survive.
    • if the parameter already exists, but have no value, the value should be set.

    As search already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search:

    
    
    add priceMin=300
    

    This at least is a bit more robust as it can deal with URLs like these:

    test.html?a?b&c&test=foo&priceMin=300
    

    Or even:

    test.html?a?b&c&test=foo&pri%63eMin=300
    

    Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.

提交回复
热议问题