Search code examples
javascriptjqueryurljsonpspecial-characters

How to create a URL from a string that replaces special characters?


I am trying to make a jsonp request from inside an iframe. For some reason, it does not seem to work. See this question.

I am now trying to attach a script tag to the head of document. Now i need to generate src for that by adding parameters of an object, which may contain some special characters, that should be converted to their codes.

Is there any javascript function for that ? There must be in the jquery as it would be requiring the same for its jsonp or ajax calls.

If i have to write mine, what are the characters that i should convert ?


Solution

  • To escape strings to encode in URIs, use the encodeURI() and encodeURIComponent() methods provided by Javascript API :

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

    See When are you supposed to use escape instead of encodeURI / encodeURIComponent? for detailed description.