10

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.

2
  • 3
    postcode.split(/[0-9]/)[0]; maybe? Commented Sep 9, 2013 at 19:29
  • Do you want postcodePrefix[1] to contain '1 2BB' or ' 2BB' or does it matter? Commented Sep 9, 2013 at 19:43

4 Answers 4

12

You can try something like this:

var postcode = 'AA1 2BB';
var postcodePrefix =postcode.split(/[0-9]/)[0];
Sign up to request clarification or add additional context in comments.

Comments

4

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]+/);

Comments

1
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];

1 Comment

Upvote for \d - idk why people use [0-9]
0
var m = postcode.match(/([^\d]*)/);
if (m) {
   var prefix = m[0];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.