Java Script Trim Function
By Stephen Bucaro
A "trim function" is a bit of code that removes leading and trailing blanks from
a character string. You might use a trim function to clean up the data from a user
input form before performing further processing on it.
Google the phrase "Java Script Trim" and you'll find that everybody and their
grandmother has a Java Script Trim function to offer. Some of these coders think the
fewer the lines used, the faster the code will work. Some enjoy being in a continuous
state of puzzlement and so they create code like this shown below.
function trim(s)
{
return s.replace(/^\s*(.*?)\s*$/,"$1");
}
This code uses a regular expression, and although regular expressions are very
powerful and useful when used in the proper application, a trim function is not
one of them. There are two problems with using a regular expression; a look at the
resulting machine code would show that it's about the slowest way to perform this
simple function, and since regular expressions are rarely required in general coding,
whenever I see them I have to review.
In any case, I offer the following code for a Java Script Trim function. My goal for
this code is not to set a speed record or demonstrate my programming prowess, but instead
to provide something that is easy to understand so that you might feel confident in
using it in your own projects.
// trim leading and trailing spaces
function trim(s)
{
var myString = s;
var j = 0;
// trim front of string
for(var i = 0; i < myString.length; i++)
{
if(myString.charAt(i) != " ")
{
break
}
else
{
j += 1;
}
}
myString = myString.substring(j, myString.length);
// trim back of string
j = myString.length;
for(var i = myString.length - 1; i >= 0; i--)
{
if(myString.charAt(i) != " ")
{
break
}
else
{
j -= 1;
}
}
myString = myString.substring(0, j);
return myString;
}
The above code simply and efficiently removes leading and trailing blanks from a
character string. Now if you regular expression lovers are such hot shots, send me
a template that (removes not replaces) blanks within a character string.
More Java Script Code: • Use JavaScript parseInt() and parseFloat() to Convert Strings to Numbers • JavaScript to Set Checkbox to Readonly • JavaScript Code to Add or Remove Specific Elements of an Array • Easy HTML5 Drag and Drop • Calculators for Your Website : Fahrenheit to Celsius Converter • Introduction to HTML5 Canvas • Java Script Math Object Trigonometric Methods • Easy Java Script Windows • Regular Expression Basics : Match a Set of Characters • Password Protection Using the JavaScript Cookie Method
|