views:

32

answers:

2

Hi,

I am encoding a string that will be passed in a url (get). But, if I use escape, encodeURI or encodeURIcomponent, & will be replaced with %26amp%3B and I want it to be replaced with just %26... What am I doing wrong?

Dodo

+1  A: 

If you did literally this:

encodeURIComponent('&')

Then the result is %26, you can test it here. Make sure the string you are encoding is just & and not & to begin with...otherwise it is encoding correctly, which is likely the case. If you need a different result for some reason, you can do a .replace(/&/g,'&') before the encoding.

Nick Craver
... that is probably his problem.
Pekka
+2  A: 

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&/g, "&"));
Andy E