我愿意做以下事情:
我有:
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, '');
最佳答案
首先,将所有出现的 ,
替换为 .
,然后将非数字字符(.
除外)替换为 ''
:
distance2 = distance2.replace( /,/g, '.').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, '.'));
关于Javascript - 如何正确使用replace()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44770393/