Decoding URL parameters with JavaScript

后端 未结 5 707
离开以前
离开以前 2020-11-27 19:22

This should be a simple task, but I can\'t seem to find a solution.

I have a basic string that is being passed through as a query string parameter like this one:

5条回答
  •  伪装坚强ぢ
    2020-11-27 19:59

    Like it was pointed out already, decodeURI function doesn't convert + to space, but there are some things worth to realize here:

    • decodeURI is meant to be used for whole URI, i.e. it doesn't decode separators like ?, &, =, +, etc.
    • for decoding parameters decodeURIComponent should be used
      (worth to have a look at: What is the difference between decodeURIComponent and decodeURI? )
    • string that you are trying to decode might actually contain + encoded as %2B, thus you should not replace + after the conversion since you might lost + signs that you actually want there, e.g. something?num=%2B632+905+123+4567 should become:
      something?num=+632 905 123 4567
      since you are probably going to extract the number: +632 905 123 4567

    So the correct way to do this is:

    var str = 'something?num=%2B632+905+123+4567';
    decodeURIComponent( str.replace(/\+/g, '%20') );
    

提交回复
热议问题