Remove Blank Spaces From Ends of a String
By Stephen Bucaro
In programming we frequently find the need to remove blank spaces from the ends
of strings. For example when accepting user input from a form, it's good practice
to submit the input string to a blank space stripping function, even if you don't
know for sure if there are any blank spaces on the ends of the input string.
The String object's trim method removes blanks from both ends of a string.
An example of using the trim method is shown below.
<script>
var inputStr = " input string ";
alert("[" + inputStr + "]");
var cleanStr = inputStr.trim();
alert("[" + cleanStr + "]");
alert("[" + inputStr + "]");
</script>
In the code above, the first alert box will show the string, within brackets, with blank
spaces on both ends. The second alert box will show the string with leading and trailing
blank spaces removed. The third alert box will again display the first string with with
blank spaces on both ends. This is to remind you that the trim method does
not modify the initial string, it returns a new string.
The trim method is supported in Firefox 3.5 and higher, and Internet Explorer 9
and higher. If you want to perform the same function in older browsers you can use
the String object's replace method with a regular expression, as shown below.
<script>
var inputStr = " input string ";
alert("[" + inputStr + "]");
var cleanStr = inputStr.replace(/^\s+|\s+$/g, "");
alert("[" + cleanStr + "]");
</script>
More Java Script Code: • The break Statement • Java Script Include a Backslash Character in a String • Using the Java Script eval() Function • A Brief History of JavaScript • The Screen Object • Accessing Web Page Elements • The for Loop • Convert a Number to a String • Java Script Reserved Words • Compare Two Strings
|