Regex replace string which is not float

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?


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

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".

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 "". 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;

Need Your Help

Count non-symmetric bytes

language-agnostic math binary bit-manipulation

I am looking for a clean way to list the (8 bit) integers whose binary representation is not the same as another integer up to rotation and reflection.

is it possible to iterate two items simulataneously using foreach in jstl?

java model-view-controller spring jsp jstl

i have two items from my model and i want to iterate them at the same using jstl foreach. how can i achieve this using a correct syntax?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.