home

Quickies, by Andrea Olivato

text

Trim,ltrim & rtrim in #javascript

Simple class to trim,ltrim and rtrim as it’s common in other languages.

Below you will find usage examples.

trim = {
	both : function(str,ch) { # Equivalent to trim
		return trim.lead(trim.trail(str,ch),ch);
	},
	lead : function(str,ch) { # Equivalent to ltrim
		if (!ch)
			ch="\\s"
		return str.replace(
			new RegExp("^["+ch+"]+", "g"), ""
		);
	},
	trail : function(str,ch) { # Equivalent to rtrim
		if (!ch)
			ch="\\s";
		return str.replace(
			new RegExp("["+ch+"]+$", "g"), ""
		);
	}
}

Usage Examples

s = "  string  ";

# Trim both left and right, every type of char
alert(trim.both(s));

# Trim only right, and just look for \n
alert(trim.trail(s,"\\n"));

2 years ago

May 29, 2009
Comments (View)
blog comments powered by Disqus