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

标签 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
    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/

相关文章:

javascript - 如何使用 javascript/jquery 获取此时间戳格式?

javascript - 如何使用 jQuery 组合淡出和删除处理

javascript - 如何在highcharts中绘制值为0的列

JavaScript 时间比较

javascript - 在 JavaScript 中获取对象名称

javascript - Rails 将 JavaScript 对象存储到模型的有效方法?

javascript - 编写事件处理程序时对一些事情感到困惑

javascript - Jquery - 如何定义用户定义的 jquery 函数?

Javascript:切片和附加 keyValue 后重复数组不正确

javascript - 为什么 XMLHttpRequest 没有返回响应?