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.
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, "") } //--> </SCRIPT> </HEAD> <BODY> <H1>Trimming Trailing 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> That's all there is to it. |