-1

I have a string and want to wrap non-numbers with double quotes (if they don't have them already). What is the best way to detect a non-number with a regex?

These are numbers: 123.43, 13827. These are non numbers: Hello, 2011-02-45, 20a, A23.

Here is the regex I currently have but does not handle the case where a non-number starts with a digit (so 2011-02-45 is not picked up).

str = str.replace(/(['"])?([a-zA-Z0-9_\-]+)(['"])?:/g, '"$2":');
str = str.replace(/:(['"])?([a-zA-Z_]+[a-zA-Z0-9_]*)(['"])?/g, ':"$2"');
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Martin Drapeau
  • 1,484
  • 15
  • 16
  • Given the input of `Hello, 2011-02-45, 20a, A23.` you expect the output to be `Hello, 2011-02-45, 20"a", "A"23.`? Or am I misunderstanding? Also, if that's correct, what should happen with `Hello, 2011-02-45, 20abc, A23.`? Perhaps `Hello, 2011-02-45, 20"abc", "A"23.` – David Thomas Dec 22 '11 at 15:05
  • Given this: `Today is 2011-12-22 the 3rd day of 2011`. YOu would get this: `"Today" "is" "2011-12-22" "the" "3rd" "day" "of" 2011`. So only numbers do not get wrapped by double quotes. – Martin Drapeau Dec 22 '11 at 15:19

3 Answers3

3

How about this:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Taken from: Validate decimal numbers in JavaScript - IsNumeric()

Community
  • 1
  • 1
alessioalex
  • 62,577
  • 16
  • 155
  • 122
  • That's not a regex. I would like to wrap any non number in a string using a replace. Sorry if that wasn't clear. – Martin Drapeau Dec 22 '11 at 15:06
  • 2
    @MartinDrapeau You're very wrong! This anser is very useful! You can use it in an if statement, and if it returns `FALSE`, wrap quotes around it like this: `if(!isNumber(x)) { x = '"'+x+'"'; }` – Tim S. Dec 22 '11 at 15:18
  • 1
    @Martin: allessioalex is saying "you don't need a regex", and he's absolutely right. Why make your code needlessly complicated (and incomplete - as his function calls catch *all* cases)? – Ether Dec 22 '11 at 20:54
1

I found the solution by reading another question. This is it: str.replace(/(['"])?([a-zA-Z0-9_\-]*[a-zA-Z_\-]+[a-zA-Z0-9_\-]*)(['"])?/g, '"$2"');

The trick is to ensure there is a non-digit in the match.

Martin Drapeau
  • 1,484
  • 15
  • 16
0

you can do something like this, which is alot quicker than regexp!

str = +str||false;

str = 123.4 or, false when not a number

This is to typecast "str" into a real number or leave it as a string you can..

str = +str||str||false;

to take that to the next step, you can check your output:

if(typeof(str)=='string'){
    //str is a string
}
paulcol.
  • 2,910
  • 1
  • 21
  • 19