Custom trim() functions in Javascript

I come from a database background, so I have always taken Oracle’s trim() functions for granted. In short, the trim() function removes spaces at the start and end of a string, the ltrim() function removes spaces at the start (ie. left side) of a string, and finally the rtrim() function removes spaces at the end (ie. right side) of a string. As I dabble into web development nowadays, I thought it would be handy to have similar functions in Javascript at my disposal.

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


function ltrim(txt) {
	return txt.replace(/^s+/,"");
}


function rtrim(txt) {
	return txt.replace(/s+$/,"");
}

Below are some usage examples.

alert(trim(' hello '));
// This should return 'hello'; spaces on both sides is removed

alert(ltrim(' hello '));
// This should return 'hello '; only space on left side is removed

alert(rtrim(' hello '));
// This should return ' hello'; only space on right side is removed

Leave a Reply

Your email address will not be published.