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
I think it's very fun to come up with ways to solve this. Below are some.
(All functions below assume argument is a single character. Change to n[0]
to enforce it)
function isCharDigit(n){
return !!n.trim() && n > -1;
}
function isCharDigit(n){
return !!n.trim() && n*0==0;
}
function isCharDigit(n){
return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
}
var isCharDigit = (function(){
var a = [1,1,1,1,1,1,1,1,1,1];
return function(n){
return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
}
})();
function isCharDigit(n){
return !!n.trim() && !isNaN(+n);
}
var str = ' 90ABcd#?:.+', char;
for( char of str )
console.log( char, isCharDigit(char) );
Simple function
function isCharNumber(c){
return c >= '0' && c <= '9';
}
This seems to work:
Static binding:
String.isNumeric = function (value) {
return !isNaN(String(value) * 1);
};
Prototype binding:
String.prototype.isNumeric = function () {
return !isNaN(this.valueOf() * 1);
};
It will check single characters, as well as whole strings to see if they are numeric.
Just use isFinite
const number = "1";
if (isFinite(number)) {
// do something
}
If you are testing single characters, then:
var isDigit = (function() {
var re = /^\d$/;
return function(c) {
return re.test(c);
}
}());
will return true or false depending on whether c is a digit or not.
A simple solution by leveraging language's dynamic type checking:
function isNumber (string) {
//it has whitespace
if(string.trim() === ''){
return false
}
return string - 0 === string * 1
}
see test cases below
function isNumber (str) {
if(str.trim() === ''){
return false
}
return str - 0 === str * 1
}
console.log('-1' + ' → ' + isNumber ('-1'))
console.log('-1.5' + ' → ' + isNumber ('-1.5'))
console.log('0' + ' → ' + isNumber ('0'))
console.log(', ,' + ' → ' + isNumber (', ,'))
console.log('0.42' + ' → ' + isNumber ('0.42'))
console.log('.42' + ' → ' + isNumber ('.42'))
console.log('#abcdef' + ' → ' + isNumber ('#abcdef'))
console.log('1.2.3' + ' → ' + isNumber ('1.2.3'))
console.log('' + ' → ' + isNumber (''))
console.log('blah' + ' → ' + isNumber ('blah'))