URL encode sees “&” (ampersand) as “&” HTML entity

后端 未结 3 1376
迷失自我
迷失自我 2020-11-28 02:58

I am encoding a string that will be passed in a URL (via GET). But if I use escape, encodeURI or encodeURIComponent, &

相关标签:
3条回答
  • 2020-11-28 03:20

    There is HTML and URI encodings. & is & encoded in HTML while %26 is & in URI encoding.

    So before URI encoding your string you might want to HTML decode and then URI encode it :)

    var div = document.createElement('div');
    div.innerHTML = '&AndOtherHTMLEncodedStuff';
    var htmlDecoded = div.firstChild.nodeValue;
    var urlEncoded = encodeURIComponent(htmlDecoded);
    

    result %26AndOtherHTMLEncodedStuff

    Hope this saves you some time

    0 讨论(0)
  • 2020-11-28 03:22

    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.

    0 讨论(0)
  • 2020-11-28 03:43

    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, "&"));
    
    0 讨论(0)
提交回复
热议问题