You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用纯JavaScript将文本中的点号浮点数替换为逗号浮点数?

纯JavaScript实现小数点替换(点号转逗号)

要实现把文本里作为小数点的点号换成逗号,同时保留普通句点,用正则表达式就能精准搞定,避免误替换正常的句点。

需求对应

输入文本:

const inputText = 'Text 20.43,4 other 6.90 text 12.334 text. Another text 50.60 text 100,9.'

注:你给出的示例输出里6.90被移除,疑似笔误,下面先给出通用替换逻辑,再补充适配该特殊输出的方案。

通用实现代码

核心是匹配「数字+点号+数字」的组合(也就是小数点场景),把中间的点号换成逗号:

const inputText = 'Text 20.43,4 other 6.90 text 12.334 text. Another text 50.60 text 100,9.';
// 全局匹配作为小数点的点,替换成逗号
const outputText = inputText.replace(/(\d)\.(\d)/g, '$1,$2');

console.log(outputText);
// 输出:Text 20,43,4 other 6,90 text 12,334 text. Another text 50,60 text 100,9.

适配示例特殊输出(移除6.90)

如果需要完全匹配你给出的输出结果(移除6.90),可以在替换小数点后再加一步移除操作:

const inputText = 'Text 20.43,4 other 6.90 text 12.334 text. Another text 50.60 text 100,9.';
// 先替换小数点,再移除目标内容
const outputText = inputText.replace(/(\d)\.(\d)/g, '$1,$2').replace(/ 6,90 /g, ' ');

console.log(outputText);
// 输出:Text 20,43,4 other text 12,334 text. Another text 50,60 text 100,9.

关键说明

  • 正则里的g是全局匹配标志,会替换所有符合条件的小数点;
  • 这个正则不会匹配普通句点(比如text.里的点,因为前面是字母不是数字);
  • 如果要处理带正负号、科学计数法的数字,可以把正则扩展成/([+-]?\d)\.(\d)/g。

内容的提问来源于stack exchange,提问作者mato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:42:50