1

I have a string, where I need to parse it as a float, but first I need to replace it, if it is not a number (an integer or a float), so I am trying to create an regular expression to do it

My tries results in NaN

One of my best tries is

var $replace = $text.replace(/^[^d.]*/, '');
var $float = parseFloat($replace);

Can anybody tell me, what I am doing wrong?

7
  • your regex says to replace zero or more characters that are not a d or a . from the beginning of your string with nothing... What are you trying to replace/remove exactly? Commented Nov 29, 2011 at 22:06
  • I am trying to replace everything, that are not a digit (or a . (used in a float)) Commented Nov 29, 2011 at 22:13
  • Why are you prepending a dollar sign to your variables? Commented Nov 29, 2011 at 22:26
  • Can you give some examples of what $text might look like, and what you want $replace and $float to look like in those cases? Commented Nov 30, 2011 at 15:12
  • @NullUserException It depends on, which server-side programming language, I am using, and right here I am using PHP, which uses dollar signs in variables Commented Dec 4, 2011 at 20:05

3 Answers 3

2

If you really want to replace everything thats not a digit, then try this:

var $replace = $text.replace(/[^\d.]/g, '');
var $float = parseFloat($replace);

This will replace a string of "123a3d2" with a string of "12332".

Sign up to request clarification or add additional context in comments.

3 Comments

What if $text = 'hello.world'?
@NullUserException Then $float == NaN. I mean, personally, I would do a validation that this is in fact a number, rather than stripping out characters. But that's not the question the op asked.
/[^\d.]/g allow to put as many . as you want. For example 12.34.5 and 1....2...3..45 works.
2

It looks like you want to strip "non-numeric" characters from the beginning of the string before converting it to float. A naive approach would be:

var s = input.replace(/^[^\d.]+/, '');
var n = parseFloat(s);

This works for inputs like "foo123" but will fail on "foo.bar.123". To parse this we need a more sophisticated regexp:

var s = input.replace(/^(.(?!\d)|\D)+/, '');
var n = parseFloat(s);

Another method is to strip the input char by char until we find a valid float:

function findValidFloat(str) {
    for (var i = 0; i < str.length; i++) {
        var f = parseFloat(str.substr(i))
        if (!isNaN(f))
            return f;
    }
    return NaN;
}

Comments

0
if (! isNaN($text))
  $float = parseFloat($text);
else
  $float = 0; // or whatever

1 Comment

This only answers part of the question, because it doesn't address the faulty regex the OP is currently using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.