Introduction to Regular Expressions in JavaScript - Simple Usage of the Literal Text Format and the Constructor Function
(Page 5 of 6 )
Assigning them to Variables
In the following code, the regexp is assigned to a variable using the Literal Text Format.
<script type="text/javascript">
var availableString = "Hello World";
var re = /World/;
if (re.test(availableString))
alert('Matched')
else
alert('Not Matched')
</script>
In the following code, the regexp is assigned to a variable using the constructor function.
<script type="text/javascript">
var availableString = "Hello World";
var re = new RegExp("World");
if (re.test(availableString))
alert('Matched')
else
alert('Not Matched')
</script>
Using them Directly in Conditional and Looping Expressions
In the following code, the literal text format is used directly in the if-conditional expression.
<script type="text/javascript">
var availableString = "Hello World";
if ((/World/).test(availableString))
alert('Matched')
else
alert('Not Matched')
</script>
The brackets around the regexp keep it as an entity.
In the following code, the constructor function is used directly in the if-conditional expression:
<script type="text/javascript">
var availableString = "Hello World";
if ((new RegExp("World")).test(availableString))
alert('Matched')
else
alert('Not Matched')
</script>
The brackets around the regexp keep it as an entity.
I prefer to assign them to variables than to use them directly in conditional and looping expressions. I believe this makes my code more readable and easier to maintain.
Next: The Flags >>
More JavaScript Articles
More By Chrysanthus Forcha