Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

Remove Blank Spaces From Ends of a String

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.

var inputStr = "   input string   ";
alert("[" + inputStr + "]");

var cleanStr = inputStr.trim();
alert("[" + cleanStr + "]");

alert("[" + inputStr + "]");

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.

var inputStr = "   input string   ";
alert("[" + inputStr + "]");

var cleanStr = inputStr.replace(/^\s+|\s+$/g, "");

alert("[" + cleanStr + "]");

More Java Script Code:
• Java Script alert Message Box
• Java Script confirm Message Box
• JavaScript Math Object
• Get Webpage File Date and File Size
• The Screen Object
• The switch / case Structure
• Java Script Quick Reference : JavaScript toString Method Converts a Number to a String
• Java Script Include a Backslash Character in a String
• Window onload Event
• Use Escape to Replace Dangerous Characters

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro

Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2024 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268