Is it possible to create a function to put the space in a UK postcode if entered wrong?

Is it possible to create a function to put the space in a UK postcode if entered wrong?

Is it possible to put a space or remove duplicate spaces in postcode entered into Billing Code? examples of incorrect postcodes: YO223BT should be YO22 3BT or if someone typed YO22  3BT > YO22 3BT etc...

If this were javascript I would use:        string . replace ( /(\S*)\s*(\d)/ , "$1 $2" ); 

which would put one space before the last number in the string. Is it possible to do similar in a function?