2

I have the following function in javascript:

function unString(String){     
   var justNumbers = /(?=.*\d)\d*(?:\.\d*)?/;
   var result      = String.match(justNumbers);
   result *= 1;
   result = Math.round(result*100) / 100;
   return result;
}

The meaning of it is to extract the number out of every possible css value, so that it can be added or substracted or multiplied with other values: e. g.

var newPadding = unString(  $('#myID').css("padding-bottom")  )*10 + "px";

Having modified my code I would now need the regex to allow an optional minus, to allow values like "-3px" be transformed to "-3" (actually the function can't and returns "0").

[I know there are tons of optional minus regex threads on stackoverflow and other forums, but they don't match the form of my regex - I do not have much experience with regex, for creating the above one I had to do long and intense research - and so I could not modify my regex, referring to these]

[The regex is should allow digits, optional decimal point and optional minus]

Thx in advance

  • http://stackoverflow.com/questions/12643009/regular-expression-for-floating-point-numbers. Use `/-?[0-9]*\.?[0-9]+/g` – Wiktor Stribiżew Jul 22 '16 at 09:41
  • any feedback? Could you provide a fiddle if it does not? – Wiktor Stribiżew Jul 25 '16 at 06:23
  • @WiktorStribiżew Yes, it works well (I use the first version). It is really handy if you have to extract the positive/negative values from css via javascript. [I just haven't given any feedback by now, because I thought, in the terms of Stackoverflow was something like "do not post comments just to thank" or something like that. Correct me if I'm wrong. In any case: Great solution :) ) – Creative Frankenstein Jul 26 '16 at 07:55

1 Answers1

4

You can use

/-?[0-9]*\.?[0-9]+/g

See the regex demo

Explanation:

  • -? - an optional hyphen (you may replace it with [-+]? to match both - and + optionally)
  • [0-9]* - zero or more digits
  • \.? - an optional dot
  • [0-9]+ - 1 or more digits.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563