HTML and CSS Reference
In-Depth Information
EXAMPLE
var myString="She wants attention now!";
var regex = /ten/
// Literal way
var regex=new RegExp("ten");
// Constructor way
regex.test (myString);
// Looking for "ten" in
myString
or
/ten/.test ("She wants attention now!");
EXAMPLE 17.1
<html>
<head><title>Regular Expression Objects the Literal Way</title>
<script language = "JavaScript">
1
var myString="My gloves are worn for wear.";
2
var regex = /love/;
// Create a regular expression object
3
if ( regex.test(myString) ){
4
alert("Found pattern!");
}
else{
5
alert("No match.");
}
</script>
</head>
<body></body>
</html>
EXPLANATION
1
“My gloves are worn for wear.” is assigned to a variable called myString .
2
The regular expression / love / is assigned to the variable called regex . This is the
literal way of creating a regular expression object.
3
The test() method for the regular expression object tests to see if myString contains
the pattern, love . If love is found within gloves , the test() method will return true .
4
The alert dialog box will display Found pattern! if the test() method returned true .
5
If the pattern / love/ is not found in myString , the test() method returns false , and
the alert dialog box will display its message, No match .
EXAMPLE 17.2
<html>
<head>
<title>Regular Expression Objects with the Constructor</title>
<script language = "JavaScript">
1
var myString="My gloves are worn for wear.";
Search WWH ::




Custom Search