“regex.match is not a function” when called on a JavaScript rexex

I’m trying to get the major part of a UK postcode. For example, the following are expected…

M34EF -> M3

M3 4EF -> M3

I already have the postcode (and just the postcode) in a JavaScript variable. Based on a regex I found here, I thought the following should work…

var regex = /^[A-Z0-9]{3}([A-Z0-9](?=s*[A-Z0-9]{3}|$))?/;
var major = regex.match(postcode);

…but this gives the error shown above.

What am I doing wrong? Or, is there a better way to do this? Thanks

Answer

Because .match should be called on your postcode string.

postcode.match(regex)

It is String.prototype method. Check here