How can I replicate this PHP code into Javascript ?? It takes a number like 2-9999 (serial number) and converts it into a NUMBER ... 2-999 would be a different value when converted.
function esn_to_num($esn)
{
if (($tmp = explode('-', $esn))) {
if (sizeof($tmp) == 2
&& my_isnum($tmp[0])
&& my_isnum($tmp[1])
) {
$esn = (($tmp[0] << 23) | $tmp[1]);
} else {
$esn = -1;
}
} else {
$esn = -1;
}
return $esn;
}
I added a dependency function below
// dependency function
/*****************************************************************************
* CHECKS IF A STRING REPRESENTS A NUMBER
******************************************************************************/
function my_isnum($str, $negative=false, $decimal=false)
{
$has_decimal = false;
$len = strlen($str);
if ($len > 0) {
$valid = true;
for ($i=0; $valid && $i<$len; $i++) {
if (!($str[$i] >= '0' && $str[$i] <= '9')) {
if ($str[$i] == '-') {
if (!$negative || $i != 0) {
$valid = false;
}
} else if ($str[$i] == '.') {
if (!$decimal || $has_decimal) {
$valid = false;
}
} else {
$valid = false;
}
}
}
} else {
$valid = false;
}
return $valid;
}
php syntax is pretty similar to JS.
Just take the variables and remove the
$
, and declare them with thevar
keyword.Then you need to replace all your php functions with equivalent JS ones. Look up "javascript equivalents of
explode
,sizeof
.Follow the same process to rewrite
my_isnum
in javascript (clearly not a native php function).edit: after seeing your update, I realize there is probably already a good chunk of code on Stack Overflow (or elsewhere) which will what
my_isnum
does. Either search "js function to determine if string is number" or ask that in a seperate question here.You can do all this in chromes javascript console, and keep iterating until you stop getting errors. If you run into a specific problem and are stuck, thats a good point to ask about it on Stack Overflow.