首页 > 解决方案 > 如何过滤英国邮政编码

问题描述

我正在尝试将英国邮政编码的第一部分与我保存在 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 和 'BA' 如果我输入 BA33HT,谁能帮我找到(例如)'B'?

标签: javascriptvue.jsfilterpostal-code

解决方案


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.


推荐阅读