I need to check whether justPrices[i].substr(commapos+2,1)
.
The string is something like: \"blabla,120\"
In this case it would check whether \'0
var Is = {
character: {
number: (function() {
// Only computed once
var zero = "0".charCodeAt(0), nine = "9".charCodeAt(0);
return function(c) {
return (c = c.charCodeAt(0)) >= zero && c <= nine;
}
})()
}
};
you can either use parseInt
and than check with isNaN
or if you want to work directly on your string you can use regexp like this:
function is_numeric(str){
return /^\d+$/.test(str);
}
The shortest solution is:
const isCharDigit = n => n < 10;
You can apply these as well:
const isCharDigit = n => Boolean(++n);
const isCharDigit = n => '/' < n && n < ':';
const isCharDigit = n => !!++n;
if you want to check more than 1 chatacter, you might use next variants
Regular Expression:
const isDigit = n => /\d+/.test(n);
Comparison:
const isDigit = n => +n == n;
Check if it is not NaN
const isDigit = n => !isNaN(n);
isNumber = function(obj, strict) {
var strict = strict === true ? true : false;
if (strict) {
return !isNaN(obj) && obj instanceof Number ? true : false;
} else {
return !isNaN(obj - parseFloat(obj));
}
}
output without strict mode:
var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;
isNumber(num);
isNumber(textnum);
isNumber(text);
isNumber(nan);
true
true
false
false
output with strict mode:
var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;
isNumber(num, true);
isNumber(textnum, true);
isNumber(text, true);
isNumber(nan);
true
false
false
false
As far as I know, easiest way is just to multiply by 1
:
var character = ... ; // your character
var isDigit = ! isNaN(character * 1);
Multiplication by one makes a number from any numeric string (as you have only one character it will always be an integer from 0 to 9) and a NaN
for any other string.
I wonder why nobody has posted a solution like:
var charCodeZero = "0".charCodeAt(0);
var charCodeNine = "9".charCodeAt(0);
function isDigitCode(n) {
return(n >= charCodeZero && n <= charCodeNine);
}
with an invocation like:
if (isDigitCode(justPrices[i].charCodeAt(commapos+2))) {
... // digit
} else {
... // not a digit
}