Javascript-如何正确使用replace()函数

Javascript-如何正确使用replace()函数,javascript,Javascript,我愿意做以下工作: 我有: 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 distanc

我愿意做以下工作:

我有:

    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, '');

首先,将所有出现的
替换为
,然后将非数字字符(除了
)替换为
'

其中:

/,/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 '').
第一次将
“5,55 KM”
转换为
“5.55 KM”
,然后第二次将后者转换为
“5.55”

注意:如果您只有一个逗号,或者只对第一个遇到的逗号感兴趣,那么您可以使用:
replace(',',')
而不是
replace(/,/g')

如果仅使用浮点表示,则可以使用
parseFloat
而不是第二个
replace

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

您需要将replace值重新分配给变量

i、 e


replace
的工作原理是“查找此字符串并替换为此字符串”。第一个参数是您要查找的参数,第二个参数是替换它的参数。因此,在您的代码中,您将用零替换

distance2.replace( /[^\d\.]*/g, '');
它也不会编辑字符串“in-place”,因此需要将
distance2
变量指定给返回值。同样,对于这样一个简单的工作,您不需要使用正则表达式。您只需输入一个字符串作为第一个参数,
replace
将找到该参数的所有匹配项。我会这样做:

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

进一步阅读:


您期望的结果是什么?抛出和打印是什么意思?你的意思是返回吗?@AliSomay in
distance 2
我想看看
5.5
的效果,但如果你能解释一下括号内的内容,我会非常感激,例如
replace(/,/g')
replace(/[^\d\.]+/g'))
@Folky.H如果你想了解那里发生了什么,你应该做一些正则表达式教程。如果你不懂正则表达式,那就有点复杂了。或者,您可以使用字符串作为第一个参数,如我的回答中所述:P@ibrahimmahrir谢谢!这并没有解决这样一个事实:
正在被零替换。
distance2.replace( /[^\d\.]*/g, '');
distance2 = distance2.replace(',', '.');