michaelp0730
1/19/2015 - 6:29 PM

John Resig - String Trim

function trim(str) {
	return str.replace(/^\s+|\s+$/g, "");
}


// an alternative approach to double-replacement of whitespace in a string
// this approach performs two replace's. One at the beginning of the string, and one at the end
function trim(str) {
	return str.replace('^\s\s*/, '')
			  .replace(/\s\s*$/, '');
}


// here is another approach that uses a regex to trim the beginning of the string,
// and the slice() method to trim the end of the string
function trim(str) {
	var str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
		
	while (ws.test(str.chatAt(--i)));
	return str.slice(0, i + 1);
}