-1

I want to url encode a string in javascript:

but these 2 function calls give the same result:

encodeURI('g0sceq3EkiAQTvyaZ07C+C4SZQz9FaGTV4Zwq4HkAnc=') === decodeURI('g0sceq3EkiAQTvyaZ07C+C4SZQz9FaGTV4Zwq4HkAnc=');  // true

both return g0sceq3EkiAQTvyaZ07C+C4SZQz9FaGTV4Zwq4HkAnc=.

Should the + sign and = sign not be encoded?

I thought = would be %3D and + would be %2B?

dagda1
  • 26,856
  • 59
  • 237
  • 450
  • 1
    `encodeURI` doesn't encode all characters, just ones "unsafe" for URIs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#Description – gen_Eric Jan 30 '19 at 19:30
  • how can I encode all characters – dagda1 Jan 30 '19 at 19:31
  • 1
    `encodeURI()` encodes special characters, except: `, / ? : @ & = + $ # ` .(Use `encodeURIComponent()` to encode these characters). ref: https://www.w3schools.com/jsref/jsref_encodeuri.asp – Daniel Gale Jan 30 '19 at 19:32
  • 1
    @dagda1 Why would you _want_ to encode all characters? – jhpratt Jan 30 '19 at 19:34

2 Answers2

3

Use encodeURIComponent and decodeURIComponent. Note, neither function is idempotent; If you accidentally double-encode a component, you will have to double-decode it -

console.log
  ( encodeURIComponent ("=")     // %3D
  , decodeURIComponent ("%3D")   // =

  , encodeURIComponent ("%3D")   // %253D
  , decodeURIComponent ("%253D") // %3D

  , encodeURIComponent (encodeURIComponent ("="))     // %253D
  , decodeURIComponent (decodeURIComponent ("%253D")) // =
  )
  
Mulan
  • 129,518
  • 31
  • 228
  • 259
0

The other answer does not answer your question.

The answer is: you think + should be encoded but it is a safe URI character. See Safe characters for friendly url

const a = encodeURI("a%")
const b = decodeURI("a")

console.log(a)
console.log(b)
console.log(a === b) /// false
Danie A
  • 811
  • 8
  • 18