15

I need to pass some parameters in the url and they can have special characters like ", spanish Ñ or ñ, : spaces and accents.

What is the propper way to encode them before adding to the url or in case I got in the html like that, read them?

I tried this:

arrayData[i] = pair[1].replace('+', " ").replace('%22', "\"");

But just get working with + or spaces, not both at the same time or in 2 lines:

    arrayData[i] = pair[1].replace('+', " ");
    arrayData[i] = pair[i].replace('%22', "\"");
Biribu
  • 3,615
  • 13
  • 43
  • 79
  • not exactly a duplicate - that's for encoding non-alphabetic characters only, which is the common case. Here, he needs to encode alphabetic but non-english/non-standard alphabetic characters. – mechalynx Sep 12 '14 at 11:45
  • Yeah, sorry, itchy trigger-finger. – Andy Sep 12 '14 at 11:55

2 Answers2

17

You can try encodeUri Built-in function, for example

encodeURI('coño funcionó!')
Manjar
  • 3,159
  • 32
  • 44
  • 1
    This. But be careful to read up on both [encodeURI](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) and its brother, [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) before using either. – mechalynx Sep 12 '14 at 11:47
  • Where I have to put this? I want to have the html in an android and ios app. So I would have to encode parameters before adding them, don't I? – Biribu Sep 12 '14 at 11:48
  • Is easier to get all the url with your parameters and then just encode it before send it. – Manjar Sep 12 '14 at 11:51
  • It works, thanks. I just had to read a little bit – Biribu Sep 12 '14 at 13:55
  • 4
    Upvoted solo por el texto de la función :) – Ihor Patychenko Mar 23 '15 at 23:41
  • Hi Biribu, pleae can you paste an example of how you got it to work. thanks. – Unbound Feb 04 '18 at 08:16
1

Previous answer is correct. JavaScript has built in functions for fulfilling this kind of tasks.

You can try to investigate these functions in w3schools.com. Here are the links with basic information and live "Try it out" feature:

  • encodeURI - takes string with your characters and encodes it into plausible for url style ( encoding spaces and non ANSII chars )
  • decodeURI - takes encoded string and decodes it to initial state
zmii
  • 4,123
  • 3
  • 40
  • 64