正则表达式替换部分字符串逗号

时间:2016-02-29 01:46:40

标签: javascript regex jqplot

所以我有一个名为' str' (我使用JQPlot,因此只使用变量名称。)

str的格式是' Date,Time,PointValue'所以这方面的一个例子是:

12/12/2015, 14:07, 7.894

我正在使用JQPlot上的pointValue舍入问题,所以我在荧光笔中使用tooltipFormatString: " %.2f"将所有值四舍五入到两位小数。然而,这对整个'变量并弄乱字符串的日期和时间部分。一个例子是:124123231774.00, 7.89 - 这对于PointValue显然有用,但不适用于日期/时间。

所以我试着编写一个Regex表达式,它只会在最后一个逗号后格式化数据。因此它会忽略日期和时间,但随后会将PointValue格式化为'%。2f'所以它舍入到两位小数。

我看过以下内容: regex to remove multiple comma and spaces from string in javascript Replace the last comma in a string using Regular Expression

我仍然被困住,所以任何帮助和解释将不胜感激。我现在有类似的东西显然不起作用。

            function tooltipContentEditor(str, seriesIndex, pointIndex, plot) {
            str = str.replace(Expression Here);

            return "<span style='color:black;'><font style ='font-weight:900;'>" + plot.legend.labels[seriesIndex] + "</font><br>" + str + "</span>";
        };

编辑:我之所以需要这个的原因是因为当我向图表中添加更多数据系列时会出现问题,从服务器中获取的一些点值会变得四舍五入并且不会出现问题显示真实价值。所以我试图格式化值而不是让它从服务器推断自己。即它会围绕7.899&#39;到&#39; 8&#39;

1 个答案:

答案 0 :(得分:1)

尝试将String.prototype.replace()RegExp /\d\.\d+$/Number.toFixed()

一起使用

&#13;
&#13;
var str = "12/12/2015, 14:07, 7.894";
var res = str.replace(/\d\.\d+$/, function(match) {
  return Number(match).toFixed(2)
});
console.log(res)
&#13;
&#13;
&#13;

相关问题