Welcome to Bucaro TecHelp!

Bucaro TecHelp
Maintain Your Computer and Use it More Effectively
to Design a Web Site and Make Money on the Web

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

Victims of Sandy Hook

Stop the Slaughter of Innocents. Congress is bought and paid for by gun lunatics and gun promotion groups. If you want to live in a safe America, help buy Congress back for America. Send a donation to Mayors Against Illegal Guns, 909 Third Avenue, 15th Floor New York, NY 10022

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:
• Use Escape to Replace Dangerous Characters
• The Conditional Operator
• Java Script Math.tan Method
• The continue Statement
• The Location Object
• The Browsers History Object
• JavaScript Operators
• Java Script Events
• Include a Quote Character in a String
• The for Loop

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-2017 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268