|
Now that we can successfully build a Regular Expression, how do we implement it into our Javascript code ? Well, if we are doing a simple replace we could do something like :
<script language="javascript">
// our string that we are going to operate on
var inputstr="this is my long test string with the word long in it, hope that the Regular Expression does not take too LONG.";
// an empty string to hold the result
var outputstr="";
// our Regular Expression
var regex=/long/gi;
// run the Regular Expression to replace any match to our Regular Expression with the word short.
outputstr=inputstr.replace(regex,"short");
// popup the string which should be
//"this is my short test string with the word short in it, hope that the Regular Expression does not take too short."
alert(outputstr);
</script>
A Match is performed in a similar way, although this time we want to let the user know if there is match or not :
<script language="javascript">
// our string that we are going to operate on
var inputstr="A1234";
// our Regular Expression
var regex=/^[A-Z]\d{4}$/g;
// do the comparison, if we have a match
if (regex.test(inputstr))
{
alert("Matches");
}
else
{
alert("Does not match");
}
</script>
Although in both of these case the input and output variables could be fields on a form and the result of the test is likely to be a little more complex that a simple popup, but I leave that for you to work into your code as the need arises.
|
|