如何过滤英国邮政编码

时间:2019-05-20 15:51:41

标签: javascript vue.js filter postal-code

我正在尝试将英国邮政编码的第一部分与我保存在JSON文件中的那些匹配。我正在Vue中这样做。

目前,如果邮政编码中有2个字母匹配,我已经设法匹配了,但是有些英国邮政编码不是以2个字母开头,有些则只有一个字母,这就是失败的地方。

查看完整代码 https://codesandbox.io/s/48ywww0zk4

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
);

如果我输入B94 5RD,有人可以帮助我找到“ B”吗?如果我输入BA33HT,有人可以帮助我找到“ BA”吗?

1 个答案:

答案 0 :(得分:0)

您可以使用与字符串开头的字母匹配的正则表达式。

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:您只能在字符串上使用.match( /^[a-zA-Z]*/ )[0];