2012-07-23 54 views
0

我需要編寫一些JavaScript功能來分析一個地址塊,並顯示錯誤 消息,如果這個傳遞地址中的郵政編碼在給定列表中(例如受奧運會的 影響)。我已經使用indexOf將地址塊的內容與受影響的郵編的列表 相匹配,並且此工作正常。使用indexOf或regex匹配郵編的開始?

但是,問題的發生是因爲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(); 
    } 
} 

回答

4

正則表達式確實是更好的,是更簡潔,更高效的表達式(將編譯到最佳匹配自動機)。這也會很簡單。

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

這裏\b表示匹配一個單詞邊界,將處理您的子串的問題。 你甚至可以在正則表達式中寫出郵編 - /\b(DT1|DT10...)\b/ - 如果你不需要其他地方的數組。

+0

謝謝OrangeDog,這工作完美。 – 2012-07-23 10:41:49