[英]How to set NULL if one group doesn't match?
我有這個正則表達式:
var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(val);
var before = Number(match[1]) + 1;
現在,當沒有任何匹配項時,我將遇到此錯誤:
未捕獲的TypeError:無法讀取null的屬性“ 1”
我該如何解決? 我想我必須設置NULL
而不是match[1]
。
嘗試這個:
var before = ( match === null ) ? 1 : match[1]
如果沒有找到匹配項,則將其設置為1
before
,否則應返回正確的匹配項。
您應該先進行一場比賽,看看是否有一場比賽。
var m = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(val);
var before = m === null ? 0 : +m[1]+1;
/* notice the Array returned by match can be immediately accessed then
cast to a number with + in front */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.