这个正则表达式在PHP中工作,但不适用于JavaScript

I am using this code in php:

php:

elseif (!preg_match('/^[A-Za-z][A-Za-z0-9]{4,31}$/', $username))
{
    echo "user name is not valid";
}
else
{
    echo "user name is OK!";
}

but I want use like this in java scipt:

javascript:

if(!preg_match('/^[A-Za-z][A-Za-z0-9]{4,31}$/', username))
{
document.getElementById("u_status").innerHTML="user name is not valid";
}
else
{
document.getElementById("u_status").innerHTML="user name is OK";
}

please help me to use this rejex in javascript

Javascript does not contain a preg_match function, what it does have is a match() function.

Thus, this line if(!preg_match('/^[A-Za-z][A-Za-z0-9]{4,31}$/', username)) needs to be changed to if(!username.match('/^[A-Za-z][A-Za-z0-9]{4,31}$/')) {

A String object in javascript has a match() function that will help you:

if(!username.match(/^[A-Za-z][A-Za-z0-9]{4,31}$/)){

} else {

}

You have to:

  • use String#match instead of preg_match()
  • use directly /<regex>/ instead of '/<regex>/'

Try this:

if(!username.match(/^[A-Za-z][A-Za-z0-9]{4,31}$/){
    document.getElementById("u_status").innerHTML="user name is not valid";
} else {
    document.getElementById("u_status").innerHTML="user name is OK";
}