Folky.H
Folky.H

Reputation: 1204

Javascript - How to use replace() function properly

I am willing to do the following:

I have :

    var distance1 = "5.5 Km";
    var distance2 = "5,5 Km";
    //The below works as expected and returns 5.5
    var finalDistance = distance1.replace( /[^\d\.]*/g, '');

    //However the below doesn't and print 55 instead
    distance2.replace( /[^\d\.]*/g, '');

    //I've tried the below too and it throws 5,5. But I want 5.5
    distance2.replace( /[^\d\.\,]*/g, '');

Upvotes: 2

Views: 1220

Answers (3)

Clonkex
Clonkex

Reputation: 3637

replace works by saying "find this string and replace with this string". The first parameter is what you want to find, the second is what to replace it with. So in your code you're replacing the , with nothing:

distance2.replace( /[^\d\.]*/g, '');

It also doesn't edit the string "in-place", so you need to assign the distance2 variable to the return value. Also, for a simple job like this you don't need to use regex. You can just input a string as the first parameter and replace will find all matches for that. This is how I would do this:

distance2 = distance2.replace(',', '.');

Further reading:

https://www.w3schools.com/jsref/jsref_replace.asp https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

First, replace all occurences of , with ., then replace non-digit characters (except .) with '':

distance2 = distance2.replace( /,/g, '.').replace(/[^\d\.]+/g, '');

where:

/,/g : matches all commas ',' that will be replaced by '.'
/[^\d\.]+ : matches any sequence of non-digit and non-dot ('.') characters that will be removed (replaced by the empty string '').

The first replace transform "5,55 KM" to "5.55 KM" then the second transform the latter to "5.55".

Note: if you only have one comma, or only interested in the first encountered one, then you could use: replace(',', '.') instead of replace(/,/g, '.').

If you are using only the float representation, you could use parseFloat instead of the second replace:

var number = parseFloat(distance2.replace(/,/g, '.'));

Upvotes: 3

Stretch0
Stretch0

Reputation: 9241

you need to reassign the replace value to the variable.

i.e.

distance2 = distance2.replace( /[^\d\.]*/g, '');

Upvotes: -1

Related Questions