Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt

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

You are here: irt.org | FAQ | JavaScript | Text | Q241 [ previous next ]

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)?'

©2013 Martin Webb