- Get link
- X
- Other Apps
Javascript Regular expressions examples
In programming regular expressions plays a important role . if you are start your career with javascript you should familier with these kinds of examples . A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations.
Regular Expression Modifiers
i – Perform case-insensitive matching
g – Perform a global match (find all matches rather than stopping after the first match)
m – Perform multiline matching
[abc]- Find any of the characters between the brackets
[0-9] – Find any of the digits between the brackets
(x|y) – Find any of the alternatives separated with |
For more information visit these sites
w3schools – JavaScript RegExp Object (w3schools.com)
geekforgeek – JavaScript Regular Expressions – GeeksforGeeks
Most Important reason to write this post is to give us some real word scenarios about regex
Here have a look some of the examples:
email validation
function ValidateEmail(mail)
{
if (/^[a-zA-Z0-9.!#$%&’+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)$/.test(myForm.emailAddr.value))
{
return (true)
}
alert(“You have entered an invalid email address!”)
return (false)
}
Date validation
function validatedate(inputText)
{
var dateformat = /^(0?[1-9]|[12][0-9]|3[01])\/-[\/-]\d{4}$/;
// Match the date format through regular expression
if(inputText.value.match(dateformat))
{
document.form1.text1.focus();
//Test which seperator is used ‘/’ or ‘-‘
var opera1 = inputText.value.split(‘/’);
var opera2 = inputText.value.split(‘-‘);
lopera1 = opera1.length;
lopera2 = opera2.length;
// Extract the string into month, date and year
if (lopera1>1)
{
var pdate = inputText.value.split(‘/’);
}
else if (lopera2>1)
{
var pdate = inputText.value.split(‘-‘);
}
var dd = parseInt(pdate[0]);
var mm = parseInt(pdate[1]);
var yy = parseInt(pdate[2]);
// Create list of days of a month [assume there is no leap year by default]
var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];
if (mm==1 || mm>2)
{
if (dd>ListofDays[mm-1])
{
alert(‘Invalid date format!’);
return false;
}
}
if (mm==2)
{
var lyear = false;
if ( (!(yy % 4) && yy % 100) || !(yy % 400))
{
lyear = true;
}
if ((lyear==false) && (dd>=29))
{
alert(‘Invalid date format!’);
return false;
}
if ((lyear==true) && (dd>29))
{
alert(‘Invalid date format!’);
return false;
}
}
}
else
{
alert(“Invalid date format!”);
document.form1.text1.focus();
return false;
}
}
Password validation
function CheckPassword(inputtxt)
{
var passw= /^[A-Za-z]\w{7,14}$/;
if(inputtxt.value.match(passw))
{
alert(‘Correct, try another…’)
return true;
}
else
{
alert(‘Wrong…!’)
return false;
}
}
- Get link
- X
- Other Apps
Comments
Post a Comment