views:

292

answers:

1

I have a regular expression that returns us and canada zipcodes as follows.

((?<US>\d{5})|(?<Can>\b[A-Z-[DFIOQUWZ]]\d[A-Z-[DFIOQU]]\ +\d[A-Z-[DFIOQU]]\d\b))

I need to do this in java script or jquery. An application that can extract only these values. For example someone could simply paste a document into the textarea, click a button and have the valid US and Canada zipcodes extracted into an array for further processing. I have looked but cannot find something that fits this requirement.

I tried Waldek Mastykarz's RegEx filter without any luck.

jQuery.extend(
    jQuery.expr[':'], {
        regex: function(a, i, m, r) {
            var r = new RegExp(m[3], 'i');
            return r.test(jQuery(a).text());
        }
    }
);


$("#idTextArea:regex('\d{5}')") US only

$("#idTextArea:regex('\\d{5}')") also tried this and host of others

where textarea input for idTextArea is the following.

"12345 ahdh 23, 6789, 65432"

I want to return only 12345 and 65432 into an array.

I am totally stumped, any help is greatly appreciated.

+1  A: 

You only need to use the String.match method, I also simplified your regular expression:

function validPostalCodes(input) {
  var r = /(\d{5}|(\b[A-Z-DFIOQUWZ]\d[A-Z-DFIOQU]\ +\d[A-Z-DFIOQU]\d\b))/g;
  return input.match(r);
}

Then you can use the above function with your textarea value:

var array = validPostalCodes($("#idTextArea").val());

And you will get an array containing the values that match your RegExp.

CMS