Search code examples
asp-classic

Insert space in specific place from right with classic asp


I'm working with some UK postcode data around 60,000 entries in a SQL 2008 database and need to manipulate a string containing a postcode.

The original form data was collected with no validation so the postcodes are held in different formats, so CA12HW can also be CA1 2HW (correctly formatted).

UK postcodes vary in length and letter / number mix with the only exception being all codes finish space number letter letter.

I am only interested in looking at the first part of the code ie before the space. Therefore I am looking at writing a piece of code that does the following:

1.Check for a space 4th from the right.

2.If there is no space insert one 4th right.

3.Split the string at the space.

So far I have:

PostCode = "CA30GX"
SpaceLocate = InStr(PostCode, " ")
If SpaceLocate = 0 Then 'Postcode needs a space

If the only constant is that there should be a space 4th right how do I insert one?

Once the space is inserted I can split the code to use as I need.

PostcodeArray = Split(Postcode, " ")

Now PostcodeArray(0) is equal to "CA3", PostcodeArray(1) is equal to "0GX"

Any help would be appreciated.


Solution

  • You can just recreate the string:

    PostCode = Left(PostCode, 3) & " " & Right(PostCode, 3)
    PostcodeArray = Split(PostCode, " ")
    

    Edit:

    PostCode = Left(PostCode, Len(PostCode) - 3) & " " & Right(PostCode, 3)