添加一个空间到英国邮政编码在正确的地方

Add a space to UK Postcode in correct place Javascript

本文关键字:邮政编码 英国 空间 一个 添加      更新时间:2023-09-26

我正试图编写一个基本函数,使我能够在英国邮政编码中添加空间,其中空格已被删除。

UK邮政编码在邮政编码字符串的最后一个数字前总是有一个空格。

一些没有空格和正确空格的例子:

CB30QB => CB3 0QB
N12NL => N1 2NL
OX144FB => OX14 4FB

要找到字符串中的最后一个数字,我是regex /'d(?='D*$)/g,我目前所使用的Javascript如下:

// Set the Postcode
var postCode = "OX144FB";
// Find the index position of the final digit in the string (in this case '4')
var postcodeIndex = postCode.indexOf(postCode.match(/'d(?='D*$)/g));
// Slice the final postcode at the index point, add a space and join back together.
var finalPostcode = [postCode.slice(0, postcodeIndex), ' ', postCode.slice(postcodeIndex)].join('');
return finalPostcode;

当我改变set postcost时,我得到以下结果:

CB30QB becomes CB3 0QB - Correct
N12NL becomes N1 2NL - Correct
CB249LQ becomes CB24 9LQ - Correct
OX144FB becomes OX1 44FB - Incorrect
OX145FB becomes OX14 5FB - Correct

似乎这个问题可能与具有相同值的两位数字有关,因为大多数其他组合似乎都可以工作。

有人知道我怎么能解决这个问题吗?

我应该用string.replace

string.replace(/^(.*)('d)/, "$1 $2");
演示

你可以使用 replace() 与regex,你需要放置空格前3个字母的结束

document.write('CB30QB'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('N12NL'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('CB249LQ'.replace(/^(.*)(.{3})$/,'$1 $2')+'<br>');
document.write('OX144FB'.replace(/^(.*)(.{3})$/,'$1 $2'));

当其他人都在回答时,.replace()更容易。但是,让我指出代码中的错误。

问题是您使用postCode.indexOf()来查找匹配的第一次出现。在本例中:

Text:     OX144FB
Match:        ^ match is correct: "4"
Text:     OX144FB
IndexOf:     ^ first occurence of "4"

要修复它,使用match对象的.index:
// Find the index position of the final digit in the string (in this case '4')
var postcodeIndex = postCode.match(/'d(?='D*$)/g).index;
var postCode = "OX144FB";
return postCode.replace(/^(.*)('d)(.*)/, "$1 $2$3");

使用String.prototype.replace方法显然是最简单的方法:

return postCode.replace(/(?='d'D*$)/, ' ');

或使用贪婪:

return postCode.replace(/^(.*)(?='d)/, '$1 ');

你之前的代码不工作,因为你正在用indexOf搜索与String.prototype.match()方法匹配的子字符串(即结束前的最后一个数字)。但是如果这个数字在字符串中出现多次,indexOf将返回第一次出现的位置。

作为题外话,当您想在字符串中查找匹配项的位置时,请使用返回此位置的String.prototype.search()方法。

这是一个老问题,但是Avinash Raj的解决方案有效,它只有在所有邮政编码都没有空格的情况下才有效。如果你有一个混合,你想正则化他们有一个空间,你可以使用这个regex:

string.replace(/('S*)'s*('d)/, "$1 $2");

DEMO -它甚至可以使用多个空格!