2013-12-13 61 views
0

如何定義在文本字段中輸入哪種類型的變量?當你按下搜索按鈕時,我希望在文本框內輸入內容,具體取決於類型,它會顯示數據庫的不同結果!定義插入哪種類型字符串或int

if(numbers 0-9){ 
    //do something 
} 
else if (letters A-Z){ 
    //do something else 
} 

如何在JavaScript中做到這一點?

+1

[正則表達式(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) – Pointy

+1

如果有什麼是數字*和*字母? (即使你不希望這樣做,也要做好準備;因爲它會發生,即使只是偶然發生。) –

回答

3

大多數去

function isNumber(n) { 
    return !isNaN(parseFloat(n)) && isFinite(n); 
} 
0

您可以嘗試做一個字符串轉換成整數:

var a = "3"; 
var b = +a; // this will try to convert a variable into integer if it can't it will be NaN 

您可以檢查是否

Boolean(+a) is true then a is Number else it's not a number 
0

你可以嘗試的方法toType由Angus Croll定義在此blog post

var toType = function(obj) { 
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() 
} 

實現:

toType({a: 4}); //"object" 
toType([1, 2, 3]); //"array" 
(function() {console.log(toType(arguments))})(); //arguments 
toType(new ReferenceError); //"error" 
toType(new Date); //"date" 
toType(/a-z/); //"regexp" 
toType(Math); //"math" 
toType(JSON); //"json" 
toType(new Number(4)); //"number" 
toType(new String("abc")); //"string" 
toType(new Boolean(true)); //"boolean" 
相關問題