0

I'm trying to match the first part of a UK postcode to those that I have held in a JSON file. I'm doing this in Vue.

At the moment I have managed to match the postcode if it has 2 letters that match, but some UK postcodes do not start with 2 letters, some just have the one and this is where it fails.

See here for full code https://codesandbox.io/s/48ywww0zk4

Sample of JSON

{
  "id": 1,
  "postcode": "AL",
  "name": "St. Albans",
  "zone": 3
},
{
  "id": 2,
  "postcode": "B",
  "name": "Birmingham",
  "zone": 2
},
{
  "id": 3,
  "postcode": "BA",
  "name": "Bath",
  "zone": 5
}
let postcodeZones = this.postcodeDetails.filter(
  pc => pc.postcode
          .toLowerCase()
          .slice(0, 2)
          .indexOf(this.selectPostcode.toLowerCase().slice(0, 2)) > -1
);

Can anyone help me find (for example) 'B' if I type B94 5RD & 'BA' if I type BA33HT?

Ash Bryant
  • 15
  • 4

1 Answers1

0

You can use a regular expression that matches the alphabetical letters at the start of a string.

function getLettersBeforeNumbers( postcode ) {
  return postcode.match( /^[a-zA-Z]*/ )[0];
}

let a = getLettersBeforeNumbers( 'B94 5RD' );
let b = getLettersBeforeNumbers( 'bA33HT' );
let c = getLettersBeforeNumbers( '33bA33HT' );

console.log( a, b, c );

/** EXPLANATION OF THE REGEXP

  / ^[a-zA-Z]* /
  
  ^ = anchor that signifies the start of the string
  [  ... ] = select characters that are equal to ...
  a-z = all characters in the alphabet
  A-Z = all capatilised characters in the alphabet
  * = zero or more occurances
**/

PS: You can just use the .match( /^[a-zA-Z]*/ )[0]; on your string.

Rob Monhemius
  • 4,822
  • 2
  • 17
  • 49
  • Hi, I must be stupid, as I'm not sure how to implement this? Can you help? :/ – Ash Bryant May 22 '19 at 15:42
  • I suspect you may want to use `string.startsWith` instead of `string.indexOf` + `> -1`-check. ( Provided you don't have to support old browsers. ). Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith – Rob Monhemius May 23 '19 at 16:55