Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Javascript Trim (See related posts)

Adds trim function to javascript string object.
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

Comments on this post

cornflakesuperstar posts on Dec 13, 2005 at 00:23
The trim function isn't quite working properly
eg. try:
<body onload="test()">
<script>
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
function test() {
var str = " a ";
alert("Original string: '" + str + "'");
str = str.trim();
alert("Incompletely stripped string: '" + str + "'");
}
</script>


ie. It doesn't strip all whitespace. This is because the regular expression should be: this.replace(/^\s+|\s+$/g, "");

eg. String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
steste posts on Feb 23, 2006 at 11:10
This should work...
// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}
joshuak92 posts on May 16, 2007 at 14:06
you have to call it with str.trim NOT str.trim()
joshuak92 posts on May 16, 2007 at 14:07
Sorry, that won't work either
choonkeat posts on Jul 28, 2007 at 00:49
missing "g" behind the regexp

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
SteveL posts on Jan 30, 2008 at 01:03
This post compares a variety of JavaScript trim implementations.
RyanD posts on Jun 25, 2008 at 07:10
Definitely different ways of implementing this. Have a look at this article What is JavaScript trim?
RyanD posts on Jun 25, 2008 at 07:13
Sorry got the url wrong, here's the correct one: What is JavaScript trim?

You need to create an account or log in to post comments to this site.


Click here to browse all 5137 code snippets

Related Posts