gpt4 book ai didi

javascript - 将邮政编码的开头与indexOf或正则表达式匹配?

转载 作者:行者123 更新时间:2023-11-28 16:15:27 27 4
gpt4 key购买 nike

我需要编写一些 JavaScript 功能来分析地址 block 并显示错误如果此递送地址中的邮政编码位于给定列表之一内(例如,将受到奥林匹克)。我已经使用indexOf将地址 block 的内容与列表进行匹配受影响的邮政编码,这工作正常。

但是会出现问题,因为以 DW3 开头但不受影响的邮政编码将显示受影响的消息,因为 indexOf 正在获取 W3。正如你在我的中看到的下面的代码我尝试匹配邮政编码前面的空格即“DW3”,但这根本不起作用,我不知道为什么。

不幸的是,也许正则表达式是匹配此模式的更好方法我对正则表达式很糟糕,所以有人可以帮忙吗?

示例地址为:

<address>Mr Jim Smith<br>
Flat, 4 Spring Lane<br>
EASTLEIGH<br>
DW3 6LS<br>
United Kingdom</address>

这是 JavaScript:

var AFFECTED_POSTCODES = ["DT1","DT10","DT11","DT2","DT3","DT4","DT5","DT6","DT8","DT9","E1","E10","E11","E13","E14","E15","E16","E18","E1W","E3","E6","E9","EC1A","EC2N","EC2R","EC2V","EC2Y","EC3M","EC3N","EC3R","EC3V","EC4","EC4M","EC4N","EC4R","EC4V","EC4Y","GU22","GU23","GU4","GU5","HA9","IG1","IG11","IG4","IG7","IG8","KT1","KT10","KT11","KT12","KT13","KT14","KT18","KT2","KT20","KT22","KT24","KT6","KT7","KT8","NW1","NW10","NW8","RH4","RH5","RM13","RM15","RM9","SE1","SE10","SE11","SE18","SE3","SE7","SL0","SL3","SW10","SW11","SW13","SW15","SW18","SW19","SW1A","SW1E","SW1H","SW1P","SW1V","SW1W","SW1X","SW1Y","SW3","SW5","SW6","SW7","SW8","TW1","TW10","TW11","TW19","TW5","TW6","TW7","TW8","TW9","UB3","UB7","W10","W11","W12","W14","W1B","W1C","W1G","W1H","W1J","W1K","W1T","W1U","W1W","W2","W3","W4","W5","W6","W7","W9","WC1A","WC1B","WC1E","WC1H","WC1N","WC1R","WC1V","WC2A","WC2B","WC2E","WC2N","WC2R"];
function checkPostcode(e){
var isAffected = false,
field = $('#delivery_details_wrapper address'),
fieldText = $(field).text();
for (var i=0; i<AFFECTED_POSTCODES.length; i++){
var patt = ' ' + AFFECTED_POSTCODES[i];
if (fieldText.indexOf(patt) !== -1) {
isAffected = true;
}
}
if (isAffected) {
if ($('.warning').length === 0) {
field.after('<p class="warning" style="margin-top: 10px; clear: both;">* Delivery to this postcode may be affected by the Olympics. For more info click <a href="'+ Arcadia.Loader.rootPath +'lib/html/olympic_message.html" class="lightbox" rel="lightbox({innerWidth: 600, innerHeight: 300})" title="Click here for postcodes that may be affected by the olympics">here</a></p>');
}
} else {
$('.warning').remove();
}
}

最佳答案

正则表达式确实会更好,更简洁、更高效(表达式将编译为最佳匹配自动机)。这也很简单。

var alternation = AFFECTED_POSTCODES.join('|');
var r = new RegExp('\\b(' + alternation + ')\\b');
var isAffected = r.test(fieldText);

这里的 \b 表示匹配单词边界,这将处理您的子字符串问题。您甚至可以在正则表达式文字中写出邮政编码 - /\b(DT1|DT10...)\b/ - 如果您在其他地方不需要该数组。

关于javascript - 将邮政编码的开头与indexOf或正则表达式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11610540/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com