Question

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)

Was it helpful?

Solution

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top