Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Intermediate
Apr 22, 2002

Trim the Leading and Trailing Spaces in a Given String


This functionality is not currently available in Javascript. However, tou can add this function to perform trimming in the strings. Trimming is useful in checking for empty spaces.
 
function RTrim(str){
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
	    var n = s.length - 1;
	    while (n >= 0 && whitespace.
indexOf(s.charAt(n)) != -1){
	        n--;
			s = s.substring(0, n+1);
		}
	}
	return s;
}

function LTrim(str){
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) {
	    var pos=0, m = s.length;
	    while (pos < m && whitespace.
indexOf(s.charAt(pos)) != -1){
			pos++;
			s = s.substring(pos, m);
		}
	}
	return s;
}

function Trim(s){
	if (s=="undefined")
		return "";
	else{
		var tmp;
		tmp = RTrim(LTrim(s));
		return tmp;
	}
}
B. Devington
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date