将所有逗号分隔的数字替换为javascript中字符串中的点分隔数字 [英] replace all comma seperated numbers to dot seperated numbers in string in javascript
本文介绍了将所有逗号分隔的数字替换为javascript中字符串中的点分隔数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设有带数字的字符串,例如, test()测试12,01%测试(12,4)12.3 s 2其他一些文本,其他文本,2,文本
Assume there are string with numbers, for instance,
test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text
我需要用逗号替换数字,用点替换相同的数字,并且不要更改其他任何内容.这样字符串就会变成
I need to replace numbers with comma to the same numbers with dot and do not change anything else. So string would become
test()测试12.01%测试(12.4)12.3 s 2其他一些文本,其他文本,2,文本
我尝试过这样的事情:
var newstr = str.replace(/^\d+,\d+$/g, "\1.\2");
或var newstr = str.replace(^ \ d * \,?\ d + $/g,"\ 1. \ 2");
or var newstr = str.replace(^\d*\,?\d+$/g, "\1.\2");
- 我认为这应该与任何逗号匹配:^ \ d * \,?\ d + $
推荐答案
您可以这样做并捕获2个组:
You could do it like this and capture 2 groups:
说明
- 组1 :捕获1个或更多数字
(\ d +)
- 匹配逗号
- 第2组:捕获1个或多个数字
(\ d +)
- Group 1: capture 1 or more digits
(\d+)
- Match a comma
,
- Group 2: capture 1 or more digits
(\d+)
var str = "test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text";
var newstr = str.replace(/(\d+),(\d+)/g, "$1.$2", ".");
console.log(newstr);
这篇关于将所有逗号分隔的数字替换为javascript中字符串中的点分隔数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文