Search the Site


bottom corner

Custom trim() functions in Javascript

This set of trim(), rtrim(), and ltrim() functions can be used to remove extraneous spaces at the start, at the end, or at both sides of a string.

This page is filed under keyword(s): 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

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): javascript.
Author: C. Peter Chen
Last updated: 20 Nov 2008

bottom corner