-1

I've read this and more articles:

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Still I have not found a solid encode/decode uri solution.

Let's say I have these variables

var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';

An unencoded url would be:

var url 'http://example.com/?first=' + first + '&second=' + second + '&third=' + third + '&fourth=' + fourth;

Later it should be in an ajax request like:

xhr = new XMLHttpRequest();
xhr.open('POST', url );

I tried this:

var url 'http://example.com/?first=' + encodeURIComponent(first);

But it does not work with #. So what is a solid encoding solution for all characters?

I don't use jQuery, just javascript.

Community
  • 1
  • 1
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • As i understand `encodeURIComponent` is for params.. And the `encodeURI` is for the URL... http://i.imgur.com/2xKpYd0.png In your case the `#` should use `encodeURIComponent` (%23) When you say it doesnt work, what do you mean ? – Pogrindis Jul 07 '16 at 08:11
  • You'll have to be a bit more specific about what "does not work with `#`" means: `encodeURIComponent('And "hash,.#$')` → `"And%20%22hash%2C.%23%24"`. – deceze Jul 07 '16 at 08:15
  • Have you tried using `escape()` ? – Krishnakumar_Muraleedharan Jul 07 '16 at 09:16
  • @Krishnakumar_Muraleedharan do not use escape, The escape and unescape functions are deprecated. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features – Pogrindis Jul 07 '16 at 10:39

2 Answers2

2

Use the encodeURIComponent when encoding uri parameters. When you encode a hashtag with that function it will result in the string "%23".

So in your example:

var first = 'Hello&and';
var second = "Let's have cite";
var third = 'And "hash,.#$';
var fourth = 'åäö other strange chars';
var url = 'http://example.com/?first=' + encodeURIComponent(first) + '&second=' + encodeURIComponent(second) + '&third=' + encodeURIComponent(third) + '&fourth=' + encodeURIComponent(fourth);

Will result in the url variable containing the string:

http://example.com/?first=Hello%26and&second=Let's%20have%20cite&third=And%20%22hash%2C.%23%24&fourth=%C3%A5%C3%A4%C3%B6%20other%20strange%20chars

More information of the encodeURIComponent function can be found here.

(citation from w3 school) This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #

A. Tapper
  • 1,261
  • 8
  • 17
-2

You can try using escape() function. This has saved me many-a times.

escape('#') does yield %23.

  • The escape and unescape functions are deprecated. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features – Pogrindis Jul 07 '16 at 10:40