RSS | Archive | Random | E-mail

About

Hi, I'm Christian Castelli, a 28 years old italian programmer located in Pisa (Italy). Here I post small snippets of code which can be useful in my work.

Links

Codepuzzling main site
Development site
ByteStrike italian blog
Follow me on Twitter

My Life Style

while(passion) {
  try {
    myLife.run();
  }catch(LifeExceptions) {  
    stronger++;
    continue;
   }
}

Following

5 June 09

Trim,ltrim & rtrim in #javascript

andreaolivato:

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

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"), ""
		);
	}
}

You can use it like this

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"));

Reblogged: andreaolivato

Tags: javascript
Comments (View)
  1. codepuzzling reblogged this from andreaolivato
  2. andreaolivato posted this
blog comments powered by Disqus
Themed by Hunson. Originally by Josh