Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JavaScript equivalent of preg_match? [duplicate]

Possible Duplicate:
How can i use preg_match in jQuery?

What is the jquery equivalent of the PHP preg_match feature? In PHP it would be :

preg_match('/[^a-zA-Z0-9]/', $str);

Which checks if the string has anything other than letters and numbers. I'd like to add some client sided validation to my site, but I've looked and looked and can't quite find the jQuery equivalent of this. Thanks.

like image 822
Supra Avatar asked Nov 11 '11 00:11

Supra


People also ask

What does Preg_match mean?

The preg_match() function returns whether a match was found in a string.

What value is return by Preg_match?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .


1 Answers

In plain JavaScript (no jQuery needed for this), you would just use the .match() method of the string object which will return null if no matches and an array if there are matches:

var str = "myteststring";
if (str.match(/[^a-zA-Z0-9]/)) {
    // contains illegal characters
}
like image 78
jfriend00 Avatar answered Oct 21 '22 09:10

jfriend00