Removing Leading and Trailing White Space


Here's another use for regular expressionsto trim leading or trailing white space. For example, I can match leading white space with the regular expression /^\s+/ and delete it with replace like this:

(Listing 20-14.html on the web site)
 <HTML>      <HEAD>          <TITLE>Trimming Leading White Space</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function trimmer()   {   var regexp = /^\s+/   document.form1.text2.value =  document.form1.text1.value.replace(regexp, "")              }            //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>Trimming Leading White Space</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" VALUE="   JavaScript is the subject."              SIZE="30">              <BR>              <INPUT TYPE="BUTTON" VALUE="Trim White Space" ONCLICK="trimmer()">              <BR>              <INPUT TYPE="TEXT" NAME="text2" SIZE="30">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 20.11.

Figure 20.11. Trimming white space.

graphics/20fig11.gif

To trim trailing white space, you can use a regular expression like this:

(Listing 20-15.html on the web site)
 <HTML>      <HEAD>          <TITLE>Trimming Trailing White Space</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function trimmer()              {  var regexp = /\s+$/  document.form1.text2.value = document.form1.text1.value.replace(regexp, graphics/ccc.gif "")            }            //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>Trimming Trailing White Space</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" VALUE="JavaScript is the subject.    " graphics/ccc.gif SIZE="30">              <BR>              <INPUT TYPE="BUTTON" VALUE="Trim White Space" ONCLICK="trimmer()">              <BR>              <INPUT TYPE="TEXT" NAME="text2" SIZE="30">          </FORM>      </BODY>  </HTML> 

That's all there is to it.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net