Javascript Regex: Testing string for intelligent query

Posted by Shyam on Stack Overflow See other posts from Stack Overflow or by Shyam
Published on 2011-01-02T16:32:58Z Indexed on 2011/01/02 16:53 UTC
Read the original article Hit count: 162

Filed under:
|
|
|

Hi,

I have a string that holds user input. This string can contain various types of data, like:

  • a six digit id
  • a zipcode that contains out of 4 digits and two alphanumeric characters
  • a name (characters only)

As I am using this string to search through a database, the query type is determined on the type of search, which i want to handle serverside using JavaScript (yes, I am using JavaScript serverside). Searching on StackOverflow, brought me some interesting information, like the .test-method, which seems perfect for my needs. The test-method returns either true or false based on the evaluation on the string using a regex object.

I am using this page as a reference: http://www.javascriptkit.com/jsref/regexp.shtml

So I am trying to determine the zipcode, by using the following very noobish regex.

var r = /[A-Za-z]{2,2}/

As far I can understand, this should limit the amount of occurrences of alphanumeric characters to a maximum of two. See beneath the output of my JavaScript console.

> var r = /[A-Za-z]{2,2}/
> var x = "2233AL"
> r.test(x)
true
> var x = "2233A"
> r.test(x)
false
> var x = "2233ALL"
> r.test(x)
true  /* i want this to be false */
> 

A little help would be really appreciated!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about regex