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.

<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 Screen Object
• The continue Statement
• How to Use a JavaScript try-catch Block to Debug
• JavaScript .big and .small to Change Text Size
• Remove Blank Spaces From Ends of a String
• Generating Random Numbers
• Use moveBy Method to Move Window by a Specific Offset
• The while Loop
• Java Script Strings
• Convert a Number to a String

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