String.toCharCode
Posted on October 27th, 2008 in JavaScript | 7 Comments »
I noticed that JavaScript has a String.fromCharCode for decoding a sequence of numbers to Unicode values but no String.toCharCode for doing the reverse. So here’s my rendition:
String.prototype.toCharCode = function(){ var r = '', string = this.split(''); for (var i in string){ r += String.charCodeAt(string[i]) + ','; } return r.substr(0,r.length - 1); } 'bob'.toCharCode(); // returns "98,111,98"
Update: version from my good friend Takashi and link to his blog on why it’s more efficient:
String.prototype.toCharCode = function(){ var str = this.split(''), len = str.length, work = new Array(len); for (var i = 0; i < len; ++i){ work[i] = String.charCodeAt(str[i]); } return work.join(','); } 'bob'.toCharCode(); // returns "98,111,98"
7 Responses
I suppose there must be the reason to do this way, but the code you wrote would not work when you add other prototype method to String. For example, do like this:
String.prototype.something = ‘foobar’;
‘bob’.toCharCode(); // returns “98,111,98,102″
It’s because you use for…in iteration to run a loop for array. for…in iteration should be very careful. For the future version of JavaScript may be able to access “DontEnum” property, or using hasOwnProperty() . But in this case, it’s easier to do as follows.
String.prototype.toCharCode = function(){
var str = this.split(”);
var len = str.length;
var work = new Array(len);
for (var i = 0; i < len; ++i)
{
work[i] = str[i];
}
return work.join(‘,’);
}
Takashi king of efficiency!
I like your changes and will add your version beneath mine. I completely agree about not using
for in. This was quick and dirty and admitting I wasn’t thinking (also I generally steer clear of adding prototypes to native objects – I only run this in Firebug when I need it.)I also like your use of
joininstead of all the string logic.Thanks!
String concatenation is (usually) very heavy in any loop, so as a general rule, you shouldn’t do that. It’s because String is basically immutable, although Firefox and Safari’s implementation of String is very efficient.
I profiled it in Firebug and it is indeed 30% faster. :]
[...] My good friend Mauvis was writing on his blog about to convert a string to comma separated ascii numbers. I commented there about his code. Here’s how I wrote, and also see his original: String.toCharCode(). [...]
Hey, nice function, but I was thinking, maybe it should return an array, as the input used by fromCharCode is an array.
What do you think?
E
I agree that as a general utility function it should return an array for greater control and to do that you would just
return work;instead ofreturn work.join(',');However, for the situations I needed it I just needed a string.