JavaScript – common String operations
April 1, 2012
Comma separated numbers:
//formats 10000045.555 as "10,000,045.555", etc
var num = 10000045.555;
//convert to string and split the string into two if there's a decimal point
var strArr = (num + '').split('.');
var n = strArr[0];
//if there's a decimal, store it
var rhs = strArr.length > 1 ? "." + strArr[1] : '';
//with the whole number, split the last 3 digits, put it at the 0th index of the array
var arr = [];
while(n.length > 3) {
arr.unshift(n.substring(n.length - 3, n.length));
n = n.substr(0, n.length -3);
}
//anything left in the string, add it to the start of the array
(n.length > 0 ) ? arr.unshift(n) :'';
console.log(arr.join() + rhs);
To capitalize a word:
//note how you can access the first character of a string, or its 0th index like you would for an array. You can also do str.charAt(0). var str = "brian"; str = str[0].toUpperCase() + str.substring(1,str.length);
To check if a String is a palindrome – “word that may be read the same way in either direction”
//when you split a string, it coverts to an array, which you can reverse and re-join it which gives you a String.
var str = "abba";
str.split('').reverse().join('') == str
Note that String “literals” are not always equal to String objects.
var a = 'a';
var b = new String('a');
a == b; // true
a === b; // false, because === checks for type AND value
typeof a; //"string"
typeof b; // "object"
//valueOf() fixes this
a.valueOf() === b.valueOf() //true
If a number is too long so that it cant be represented as a number but instead needs a String representation – you need a special way of performing operations on it. For example: to subtract 1 from a really long number(represented as a String)
function subtractOne(num) {
if(num[num.length-1]*1 === 0) {
return subtractOne(num.substr(0, num.length-1)) + '9';
}
else {
return num.substr(0, num.length-1) + ('' + num.charAt(num.length-1)*1 -1);
}
}
subtractOne('1890273492865564687318970981034899286348912374'); //prints "1890273492865564687318970981034899286348912373"