Copy link to clipboard
Copied
Is there a wildcard for any type of and amount of characters in javascript?
I'm building a javascript client-side UK postcode validator using javascript, and can get the validation to pass as long as a user types the exact amount and type of characters. However, UK postcodes are not all the same amount of characters, however the last four characters are always the same format which is:
space | numeral | alpha | alpha
So I have JS wildcards looking for this format at the end of the post code as this:
\s\d\D\D
And this works fine, but it's the fist part of the postcode which is awkward because it can be two, three or four characters long. So a postcode could look like any of the following:
A1 1AB
A12 1AB
AB12 1AB
As you can see, the last four characters will always be 'space numeral alpha alpha', but the first characters can be pretty much anything!
So what is the wildcard that will looking for any amount of and type of character?
I've tried looking on so many sources, but am not getting the answer I need. Surely an all encompassing wildcard exists like it does in SQL!
Thanks.
1 Correct answer
Regex can be a pretty powerful and at the same time confounding thing.
If the mask you seek is truly "two-to-four of any letter/number combination followed by a space followed by a number and two letters", then let me play around with this. Let's say "str" equals "AB12 1BA".
var pcMask = /^[0-9a-zA-Z]{2,4}\s{1}[0-9]{1}[a-zA-Z]{2}$/;
if(pcMask.test(str)){// if it matches
it's good, go ahead
}
else{// it doesn't match
it's bad, stop right there
}
Untested, but this should work. RegE
...Copy link to clipboard
Copied
Regex can be a pretty powerful and at the same time confounding thing.
If the mask you seek is truly "two-to-four of any letter/number combination followed by a space followed by a number and two letters", then let me play around with this. Let's say "str" equals "AB12 1BA".
var pcMask = /^[0-9a-zA-Z]{2,4}\s{1}[0-9]{1}[a-zA-Z]{2}$/;
if(pcMask.test(str)){// if it matches
it's good, go ahead
}
else{// it doesn't match
it's bad, stop right there
}
Untested, but this should work. RegExObj.test(str) just returns a boolean, true or false, if the mask is found (or not) in str. You could use str.match(RegExObj), but that would return either null if it isn't found, or an array that has a length of one if it is found.
HTH,
^ _ ^
UPDATE: I tested it locally and it works.
Copy link to clipboard
Copied
Wow! That is spot on.
Stunned that there's not just one single character like there is in SQL though, but thanks so much.
Copy link to clipboard
Copied
Glad to know that this is working, for you. And thank you for marking my answer as correct, I do appreciate it.
SQL can do the wildcard thing because it's partially a search engine, and it needs a wildcard. JS, however, being an object oriented programming language, has no need for it. Hence, the Regular Expressions introduction. You can do a LOT with RegEx.
V/r,
^ _ ^

