>> GreenByte.info By Nick Tong (quiksilv) | Supported by: TalkWebSolutions.co.uk

Trimming strings with Javascript

Here is a quick code snippet showing how you can trim strings in javascript:

// trim both sides
function trim(trimThis) {
   return trimThis.replace(/^\s+|\s+$/g,"");
}
// left trim function ltrim(trimThis) {
   return trimThis.replace(/^\s+/,"");
}
// right trim function rtrim(trimThis) {
   return trimThis.replace(/\s+$/,"");
}

Example:

...
var thisString = " welcome to my blog ";
alert(trim(thisString));
...


 
Comments
Kris Brixon's Gravatar Here is a JavaScript library that I found helpful.

JavaScript Library of ColdFusion Functions
"This is a JavaScript library that emulates many ColdFusion functions. It is useful for ColdFusion developers who are new to JavaScript or who want to maintain consistency in a ColdFusion and JavaScript mixed application. It is also useful for developers who prefer the ColdFusion (and Visual Basic) syntax of invoking functions."

http://www.leftcorner.com/index.cfm?Article=JavaSc...
# Posted By Kris Brixon | 07/10/07 18:01 | Report abusive comment
Bill's Gravatar Since Javascript is an object oriented language you can actually just extend the string class to support a trim method. I think it is a little cleaner - YMMV

String.prototype.trim = function() {
return this.replace(/^\s*|\s*$/g, "")
}

then you can use it just like this:

alert(myString.trim());

etc..
# Posted By Bill | 08/10/07 21:50 | Report abusive comment
BlogCFC was created by Raymond Camden. This blog is running version 5.5.1.