Currently I have a JavaScript program that is using Regex to detect UK postcodes.
At the minute it is just displaying them in an alert.
I am currently struggling to detect Postcodes with a space.
For example SW12 5BV, BR3 8DD
It also needs to accept Postcodes without spaces such as DE148NV, JN24HH.
Current Regex Code:
var postcodePattern = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
var resultPost = postcodePattern.test(words[i]);
if(resultPost) {
alert("Postcode detected: " + words[i]);
I have also tried various other UK postcode regex which to no avail.
Example
//var postcodePattern = /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {0,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR ?0AA)$/
I also have a function which removes all HTML Tags after the regex has taken place which has affected previous regex.
removeHTMLTags: function(aString){
var strInputCode = aString;
var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, " ");
strTagStrippedText = strTagStrippedText.replace(/ /g," ");
//Remove some escape characters
strTagStrippedText = strTagStrippedText.replace(/\(|\)|\{|\}|\[|\]|\?|\*|\+|\||\//ig," ");
//Replace multilple white spaces with single white space
strTagStrippedText = strTagStrippedText.replace(/\s+/g," ");
return strTagStrippedText; },
Any help would be grateful.
As simple as putting your space inside a character class? I am assuming you are only allowing a single space based on the re-formatting code in the second code block.
As per the comments, you are splitting you input on spaces as well here:
with the \s+ in your split regex. This means postal codes with a space get passed to your regex as two separate array items and not a single string.