8

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.

Community
  • 1
  • 1
Supra
  • 230
  • 1
  • 3
  • 7

3 Answers3

8

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
}
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
jfriend00
  • 683,504
  • 96
  • 985
  • 979
4

not jQuery but JavaScript

var myStr = "something";

/[^a-zA-Z0-9]/.test(myStr) // will return true or false.

or for clarity

var regEx=/[^a-zA-Z0-9]/;

regEx.test(myStr)

The test method is part of the RegEx object... Here is some reference

http://www.w3schools.com/jsref/jsref_regexp_test.asp

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
  • Several issues here. First `.test()` is only a method of a regular expression object, not a string. Second, you don't put quotes around the regular expression when using the `/xxx/` notation. Third, you have `myStr` in one place in `mystring` in another. – jfriend00 Nov 11 '11 at 00:38
  • @jfriend00 You should refresh your screen during the timeframe of the 5min each user gets when completing thier answer. – John Hartsock Nov 11 '11 at 00:39
  • I responded to what you originally wrote as your answer. If you don't want comments like this, your original answer should not contain so many errors as it wasn't even close to correct. – jfriend00 Nov 11 '11 at 00:40
  • 1
    @jfriend00 didnt say I dont want comments. But your comment was well after I made the modification. All I was saying was refresh your screen. – John Hartsock Nov 11 '11 at 00:41
1

If you want to match on a string, you can do it with vanilla JS:

var str = "here's my string";
var matches = str.match('/[^a-zA-Z0-9]/');

If you're trying to do it on a selector, and using jQuery, you can use:

$("div:match('/[^a-zA-Z0-9]/')")
Dan Crews
  • 3,067
  • 17
  • 20