Removing Leading and Trailing White SpaceHere'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,
That's all there is to it. |
Regular Expression ObjectsThe regular expressions we've been using are actually treated as regular expression objects in JavaScript. There are two ways to create such objectsby just assigning a pattern to a variable (as we've been doing), or by explicitly creating a new regular expression object with the new operator:
var regexp = /pattern/[modifiers]
var regexp = new RegExp("pattern",["modifiers"])
We've already seen that you can pass regular expression objects to
Table 20.1. The Properties and Methods of Regular Expression Objects
Table 20.2. The Properties of Regular Expression Objects
Table 20.3. The Methods of Regular Expression Objects
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||