I am trying to split a UK postcode string to only include the initial letters. For example, 'AA1 2BB' would become 'AA.'
I was thinking something like the below.
var postcode = 'AA1 2BB';
var postcodePrefix = postcode.split([0-9])[0];
This does not actually work, but can someone help me out with the syntax?
Thanks for any help.
I am trying to split a UK postcode string to only include the initial letters. For example, 'AA1 2BB' would become 'AA.'
I was thinking something like the below.
var postcode = 'AA1 2BB';
var postcodePrefix = postcode.split([0-9])[0];
This does not actually work, but can someone help me out with the syntax?
Thanks for any help.
Share Improve this question asked Sep 9, 2013 at 19:28 dreamviewerdreamviewer 1551 gold badge2 silver badges8 bronze badges 2 |4 Answers
Reset to default 12You can try something like this:
var postcode = 'AA1 2BB';
var postcodePrefix =postcode.split(/[0-9]/)[0];
Alternatively, you could use a regex to simply find all alphabetic characters that occur at the beginning of the string:
var postcode = 'AA1 2BB';
var postcodePrefix = postcode.match(/^[a-zA-Z]+/);
If you want any initial characters that are non numeric, you could use:
var postcodePrefix = postcode.match(/^[^0-9]+/);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
"AA1 2BB".split(/[0-9]/)[0];
or
"AA1 2BB".split(/\d/)[0];
var m = postcode.match(/([^\d]*)/);
if (m) {
var prefix = m[0];
}
postcode.split(/[0-9]/)[0];
maybe? – Matthew Commented Sep 9, 2013 at 19:29