Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q241 How do I strip leading and trailing blanks off of a string (without writing a function to treat character by character)?

irt.org | Knowledge Base | JavaScript | Text | Q241 [ previous next ]

Q241 How do I strip leading and trailing blanks off of a string (without writing a function to treat character by character)?

The following demonstrates an efficient character by character method of stripping leading and trailing spaces from a form field value, followed by a method supported by JavaScript1.2 browsers using regular expressions. The method chosen depends on the JavaScript version supported by the browser being used.

<SCRIPT LANGUAGE="JavaScript"><!--
function stripSpaces() {
    x = document.myForm.myText.value;
    while (x.substring(0,1) == ' ') x = x.substring(1);
    while (x.substring(x.length-1,x.length) == ' ') x = x.substring(0,x.length-1);
    document.myForm.myText.value = x
}
//--></SCRIPT>

<SCRIPT LANGUAGE="JavaScript1.2"><!--
function stripSpaces() {
    var x = document.myForm.myText.value;
    document.myForm.myText.value = (x.replace(/^\W+/,'')).replace(/\W+$/,'');
}
//--></SCRIPT>

<FORM NAME="myForm">
<INPUT TYPE="TEXT" NAME="myText">
<INPUT TYPE="BUTTON" VALUE="Strip White Space" onClick="stripSpaces()">
</FORM>

the following was submitted by Jay Dunning

The following is much easier to code than either the substring or regexp approaches. It is faster than the substring algorithm. Although it is slower than regexp, it will work in older interpreters:

mystring.split(" ").join("");

Feedback on 'Q241 How do I strip leading and trailing blanks off of a string (without writing a function to treat character by character)?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.