Sunday, February 24, 2013

JavaScript Strings

document.write("Hello<br />");

// concat string
var s1 = "One";
var s2 = "Two";
var concat = s1 + ", " + s2;

// string length
concat.length

// substring - zero-indexed
concat.substring(6, 3);

// last char
concat.charAt(concat.length-1);

// first occurrence of w
concat.indexOf('w')

// implicit conversion
var a1 = "2";
var a2 = 4;

var total = a1 + a2; // both treated as strings
total = a1 * a2;  // both treated as numbers

var total = Number(a1) + a2; // force string to number

var total = String(a2) + String(a2);  // force number to string