2011-11-21 66 views

回答

2

嘗試此正則表達式:

/^[\d\s]+$/ 
4
var str = "Watch out for the rock!".match(/^[\d\s]+$/g) 
1

字符\d任何數字是一樣使用[0-9]相匹配時,字符\s任何空白匹配。

要檢查一個字符串是一個數字(假設沒有點或逗號):

var regex = /^[\d]+$/; 

但是,你更簡單的方法是使用isNaN()功能。如果該函數返回true,則該數字是非法的(NaN)。如果它返回false,這是一個正確的數字。

if(!isNaN(value)) { 
    // The value is a correct number 
} else { 
    // The value is not a correct number 
} 
7

你可以嘗試像

var isSpacedNumber = (/^\s*\d+\s*$/i).test(<string value>); 

正則表達式由部分

  • 的 「^」 的說法,比賽應該從輸入
  • \ S開頭開始*意思是零或多個(*)空格(\ s)
  • \ d +表示一個或多個(+)數字(\ d)
  • \ S *意味着零個或多個(*)空白字符(\ S)字符串
  • $意味着比賽結束

沒有^和$正則表達式將捕獲的任何數量的字符串,因此「數字是123」將給予積極的指示。

More information about javascript regular expression can be found here