2012-12-07 143 views
1

僅檢查整數值我的代碼:通過正則表達式

我嘗試下面的代碼

<SCRIPT type="text/javascript"> 

var num = "10"; 
var expRegex = /^\d+$/; 

if(expRegex.test(num)) 
{ 
    alert('Integer'); 
} 
else 
{ 
    alert('Not an Integer'); 
} 

</SCRIPT> 

我得到的結果作爲Integer。其實我用雙引號聲明瞭num varibale。顯然它被認爲是string。其實我需要得到結果爲Not an Integer。如何更改RegEx以便我可以得到預期的結果。

在這種情況下,應該給出結果爲Not an Integer。但我得到Integer

回答

5
if(typeof num === "number" && 
    Math.floor(num) === num) 
    alert('Integer'); 
else 
    alert('Not an Integer'); 

正則表達式在那裏工作的字符串。因此,如果您嘗試使用除字符串之外的其他字符串,則字符串將被轉換,否則您將得到一個錯誤。而你的返回true,因爲顯然這個字符串只包含數字字符(這就是你正在檢查的內容)。使用typeof運算符代替。但是JavaScript沒有專用的類型intfloat。所以你必須自己做整數檢查。如果floor不改變該值,那麼你有一個整數。

還有一個警告。 Infinitynumber並且調用Math.floor()就會再次導致Infinity,所以您會在那裏得到誤報。你可以改變這樣的:

if(typeof num === "number" && 
    isFinite(num) && 
    Math.floor(num) === num) 
    ... 

看到你的正則表達式,你可能希望只接受正整數:

if(typeof num === "number" && 
    isFinite(num) && 
    Math.floor(Math.abs(num)) === num) 
    ... 
+1

挑剔:假陽性'Infinity'和'-Infinity' – Esailija

+0

@Esailija剛剛意識到,第二次以前:D ...我將編輯 –

+0

考慮使用'isFinite(num)'而不是「abs」並與Infinity進行比較。 – maerics

0

我認爲這是比較容易請使用isNaN()。

if(!isNaN(num)) 
{ 
    alert('Integer !'); 
} 
else 
{ 
    alert('Not an Integer !'); 
} 

萊昂

+0

將爲'10.1'返回'Integer !'。 –

2

正則表達式是用於字符串。您可以檢查typeof num == 'number'但你需要執行多個檢查花車等,還可以使用一個小位運算符檢查整數:

function isInt(num) { 
    num = Math.abs(num); // if you want to allow negative (thx buettner) 
    return num >>> 0 == num; 
} 

isInt(10.1) // false 
isInt("10") // false 
isInt(10) // true 
+0

不適用於負整數。 (雖然這可能是需要的,看到正則表達式) –

+0

@ m.buettner true,添加一個'Math.abs'就可以解決它。 – David