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.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .
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]+/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With