2

I wrote this function, the last line seems wrong* but it actually works. Can someone explain how does this stuff work ?

function convertEncoding(str,from,to) {
    var charSetObj = createobject("java", "java.nio.charset.Charset");
    var e_to = charsetObj.forName(from);
    var e_from = charsetObj.forName(to);
    return e_from.decode(e_to.encode(str)).toString();
}

I am on BlueDragon 7 and 7.1JX (not the open source)

I was inspired from this function : http://acoderslife.com/index.cfm/blog/Converting-Text-From-UTF-8-to-ISO-8859-1

* It seems that our last action is to work with the From encoding. It should be From.decode(string) and then To.encode(decoded_string)

Charles
  • 50,943
  • 13
  • 104
  • 142
lud
  • 1,941
  • 20
  • 35

1 Answers1

4

The reason it seems off is that you swapped the variable names, so they do not accurately represent the contents:

  • var e_to = charsetObj.forName(from); // Original encoding

  • var e_from = charsetObj.forName(to); // New encoding

The reason it works is because the final statement accounts for this by swapping the variables positions, so that despite their names, the code is actually doing this:

   return newEncoding.decode( originalEncoding.encode(str) ).toString();

Obviously best to fix the variable names, so you are not scratching your head when you run across this code six months from now.

function convertEncoding(str, from, to) {
    var charSetObj = createobject("java", "java.nio.charset.Charset");
    var origEncoding = charsetObj.forName( arguments.from );
    var newEncoding = charsetObj.forName( arguments.to );
    return newEncoding.decode(origEncoding.encode( arguments.str )).toString();
}
Leigh
  • 28,765
  • 10
  • 55
  • 103
  • aaaaw how could i have missed it ... thank you ! what bugs me is that the original function (see my link) actually works too. Thanks again – lud Nov 06 '13 at 22:33
  • Oh, right. I did not notice it the first time, but the variable names are essentially swapped in the blog entry too. Hence the confusion! – Leigh Nov 07 '13 at 14:03