• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 20. The RegExp Object: Working w... > Removing Leading and Trailing White ...

Removing Leading and Trailing White Space

Here’s another use for regular expressions—to 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> 

					  


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint