0

enter image description here

I am getting id from URL like this. Both are object. If I recognize it like id[0] then it gives me datatype String

But as a human I can understand one is String and another is Integer.

How can I recognize it with JS Code?

Aspile Inc
  • 119
  • 2
  • 10
  • 1
    Does this answer your question? [(Built-in) way in JavaScript to check if a string is a valid number](https://stackoverflow.com/questions/175739/built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number) – Easwar Dec 18 '20 at 11:22
  • There are limited [types](https://tc39.es/ecma262/#sec-ecmascript-language-types) in ECMAScript. The distinction you're trying to make is not recognised by the language, so you'll have to develop your own tests and apply them. What have you tried? – RobG Dec 18 '20 at 11:23
  • 2
    *"But as a human I can understand one is String and another is Integer."* No, they're both strings. One of the strings contains only digits, but that doesn't mean it's not a string. (`00501` [one of the zip codes in New York] is also a string of digits, and while you wouldn't usually write those leading zeros if writing it as a number, it would be wrong to leave them out when dealing with it as a zip code.) – T.J. Crowder Dec 18 '20 at 11:24

1 Answers1

-1

Try to parse as an integer:

function roughScale(x, base) {
  const parsed = parseInt(x, base);
  if (isNaN(parsed)) { return 0; }
  return parsed * 100;
}

console.log(roughScale(' 0xF', 16));
// expected output: 1500

console.log(roughScale('321', 2));
// expected output: 0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
  • 1
    Notice this gives wrong results for `123blah`. – Bergi Dec 18 '20 at 11:22
  • what else should you do? maybe create your own parser. I think passing numbers enclosed in strings is a bad pattern. – Mario Vernari Dec 18 '20 at 11:25
  • No, the "what else" you should do is described in the [dupetarget](https://stackoverflow.com/questions/175739/built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number). – T.J. Crowder Dec 18 '20 at 11:59
  • I am sorry, but the most voted answer of that post leverages the parseFloat (here the user mentioned "integers", but it's the same). Where is the difference, please? – Mario Vernari Dec 18 '20 at 12:01