“core” javascript file (part 1) – string trimming

I was tweeting a bit about a few simple string trimming functions. I thought it might be interesting to flesh that out a bit and also start a short blog series on what I have in my “core” javascript file. Basically this core file, or library – if you want to stretch it – contains simple utility functions that make the rest of my javascript programming simple. A lot of these functions will probably be handled if you use a mature 3rd party library like YUI or jQuery. Even so, it’s good to understand how some of these functions work. Also some of the code in “core” library contains functionality that is not in the feature set of these external libraries. I’ll start off with the trim() function, and go through other aspect of my “core” file in subsuquent posts.

The “core” file starts with a pseudo-namespace creation – the namespace being “core”:

core = new Object()

The trim function allows you to strip leading or following whitespace from a string. It’s often found in most programming languages. I find myself using it almost always when manipulating strings in compiled code.

core.trim = function(text){
	return text.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}
String.prototype.trim = function(){
	return core.trim(this)
}

The first block defines a standalone trim function. Using regular expressions it replaces out whitespace characters. We can expand upon the native String object to add-on a trim function. This ability to add-on methods to native objects really shows some of flexibility and power of javascript. This allows us to modify the String object so that any string that is created heretofore has the trim() method available to it.

You can now take an input from a textbox and trim any outside whitespace like so:

var firstName = document.getElementById('txtFirstName').value
document.write(firstName.trim())

This simplifies trimming across the board for all strings.

Advertisement

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.