我正在尝试使用此处指定的邮政编码正则表达式:UK Postcode Regex (Comprehensive)使用javascript,但它似乎不起作用。我正在使用:
var postcode = "^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$";
var aPCode = frm.PCode.value;
if (!(postcode.test(aPCode)))
{
AnError += "Invalid Postcode.\n";
}
我得到的错误是if (!(postcode.test(aPCode)))
行。 IE7(我启用了JavaScript错误的浏览器)报告错误“对象不支持此属性或方法”。这意味着我不能在字符串上使用.test
方法,但这就是它应该被使用的地方,不是吗?我似乎无法找到我的代码的错误。
答案 0 :(得分:1)
postcode
是一个字符串,而不是正则表达式。用正斜杠包装它并删除包装引号以使其成为正则表达式:
var postcode = /^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$/;
或者将正则表达式的字符串版本运行到RegExp
对象中进行转换:
var postcode = "^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$";
var postcode = new RegExp(postcode);