desbest
desbest

Reputation: 4906

Javascript cannot encode the £ sign

I have <meta charset="utf-8" /> on my website, my files are in UTF-8 encoding and I have put charset="utf-8" on the script tag - and it still doesn't work.

Below is my code

<input type="text" id="danewcontent1" name="danewcontent1" 
value="£890">

<script charset="utf-8">
function escapePercent(str) {
  return str.replace(/%/g, '%25');
}

$(function() {
    var post_id = 1;
    var daplaincontent = $("#danewcontent1").val();
    alert(daplaincontent);
    var danewcontent = escapePercent(escape(daplaincontent));
    prompt("Copy the value below into http://urldecode.org and keep clicking decrypt", danewcontent);

    // decode the URLEncode here, and keep clicking "decode"
    // https://urldecode.org
});
</script>

It encodes £ as %25A3890 which is %A3890 decoded which is �890 decoded.

I have a JS Fiddle illustrating this problem here. https://jsfiddle.net/desbest/dyz9zta6/

Upvotes: 0

Views: 49

Answers (1)

TinkerTenorSoftwareGuy
TinkerTenorSoftwareGuy

Reputation: 797

I think you need to stop trying to re-invent the wheel and use built-in browser encoding and decoding. Your simply handling the escape the way you do is not working for you.

$(function() {
    var post_id = 1;
    var daplaincontent = $("#danewcontent1").val();
    alert(daplaincontent);
    var encoded = encodeURIComponent(daplaincontent);
    alert(encoded);
    var decoded = decodeURIComponent(encoded);
    alert(decoded); // this gives back the £890
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="danewcontent1" name="danewcontent1" 
value="£890">

Upvotes: 1

Related Questions