Monday, July 26, 2010

JS tips - I

Level: Moderate

String to integer conversion (Caution with parseInt):

Remember to always include the base with parseInt, otherwise you can introduce hard to find bugs. If the string has a leading zero, it is evaluated with base 8 (Octal). Therefore "015" will return 13. The correct way is parseInt('015', 10);

A neat way is to achieve the same is to simply put a plus sign in front of the string variable. That forces a type conversion to decimal:
var s="015"
var i= +s + 2;
console.log(typeof i);
console.log(i);
//results in:
// number
// 17

Trim() for strings:

You can extend the String object to include trim, ltrim and rtrim with a little regex to strip off the surrounding white spaces.

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
String.prototype.ltrim = function() {
return this.replace(/^\s+/, '');
};
String.prototype.rtrim = function() {
return this.replace(/\s+$/, '');
};


Now you can use trim any string variables, input field values, or even string literals. For example:

<input id="firstname" onchange="value=value.trim()" />

No comments: