Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a space to UK Postcode in correct place Javascript

I am trying to write a basic function that will allow me to add a space to UK postcodes where the spaces have been removed.

UK postcodes always have a space before the final digit of the postcode string.

Some examples with no spacing and with correct spacing:

CB30QB => CB3 0QB
N12NL => N1 2NL
OX144FB => OX14 4FB

To find the final digit in the string I am regex /\d(?=\D*$)/g and the Javascript I have in place currently is as follows:

// Set the Postcode
var postCode = "OX144FB";

// Find the index position of the final digit in the string (in this case '4')
var postcodeIndex = postCode.indexOf(postCode.match(/\d(?=\D*$)/g));

// Slice the final postcode at the index point, add a space and join back together.
var finalPostcode = [postCode.slice(0, postcodeIndex), ' ', postCode.slice(postcodeIndex)].join('');

return finalPostcode;

I am getting the following results when I change the set postcost:

CB30QB becomes CB3 0QB - Correct
N12NL becomes N1 2NL - Correct
CB249LQ becomes CB24 9LQ - Correct
OX144FB becomes OX1 44FB - Incorrect
OX145FB becomes OX14 5FB - Correct

It seems that the issue might be to do with having two digits of the same value as most other combinations seem to work.

Does anyone know how I can fix this?

like image 780
Tom Pinchen Avatar asked Dec 05 '22 02:12

Tom Pinchen


1 Answers

I should use string.replace

string.replace(/^(.*)(\d)/, "$1 $2");

DEMO

like image 150
Avinash Raj Avatar answered Dec 09 '22 15:12

Avinash Raj