0

I'm looking for a good way to make sure numbers are NOT strings, before I convert it to a JSON. Any suggestions would be great. My current regex isn't quite right.

<script>

var str = '[2012,99],[2013,96],["2014","96.3"],["2015","98.7"],'; // need to ensure any stringed numbers are actually numbers.
str = str.replace(/"(\d)"/g, "$1"); // Make sure numbers are not represented as strings
str = str.replace(/,\s*$/g, ""); // remove comma at end of string
str = "["+str+"]";
console.log(str);
dataArray = JSON.parse(str); // Create output that google charts can use
console.log(dataArray);

</script>
Bridgbro
  • 269
  • 1
  • 3
  • 17
  • 3
    See http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric – PM 77-1 Jul 09 '15 at 20:21

2 Answers2

3
str = str.replace(/"([0-9.]+)"/g, "$1");

should do your job.

And using

console.log(JSON.stringify(dataArray));

helps your debugging eyes.

ikrabbe
  • 1,909
  • 12
  • 25
1

This is a better one.
Find /"(\d+(?:\.\d*)?|\.\d+)"/
Replace $1

 "     
 (                             # (1 start)
      \d+ 
      (?: \. \d* )?
   |  \. \d+ 
 )                             # (1 end)
 "
  • This is better? You're joking. – ikrabbe Jul 09 '15 at 20:53
  • Defines a integer or decimal number. Better? Probably. –  Jul 09 '15 at 20:54
  • Actually if your's is better depends on the data you want to manipulate. I like to vote for simplicity and readability. – ikrabbe Jul 09 '15 at 21:01
  • Yeah? Simplicity doesn't tell the difference between `....9..0....` and a integer and decimal number. –  Jul 09 '15 at 21:11
  • I know what you mean, but it is not always good to accept any input and do that with regular expressions. That's what I mean with, it depends on the data. Or I should better say: It depends on the source of data. If you can guarantee a special data format and just want to transform that format into something else, that is the use case for regular expressions. What you suggest is better done with JavaScript number parsing functions, as PL 77-1 suggests in the first comment to the question. – ikrabbe Jul 10 '15 at 04:32