javascript regexp在字符串末尾找到第3个字符

时间:2021-01-01 09:26:12

How do I use regexp to turn "1.500.00" into "1.500,00"? The comma is always needed before 2 last digits. So I need regexp to look at the end of the string and replace 3rd char with ",". But I can't figure out what expression to use for this.

如何使用正则表达式将“1.500.00”变为“1.500,00”?在最后2位数之前总是需要逗号。所以我需要regexp来查看字符串的结尾并用“,”替换第3个字符。但我无法弄清楚用于此的表达方式。

4 个解决方案

#1


2  

Use this:

用这个:

yourString.replace(/\.(\d\d)$/, ",$1");

#2


1  

How about not using a regexp:

如何不使用正则表达式:

var num = '1.500.00'.split('.'), 
    num1 = num.slice(0,num.length-1), 
    num2 = num[num.length-1];

alert(num1.join('.')+','+num2); //=> 1.500,00

Or without intermediate variables (num1, num2):

或者没有中间变量(num1,num2):

alert(num.slice(0,num.length-1).join('.')+','+num[num.length-1]); /=> 1.500,00

Or

要么

alert([ num.slice(0,num.length-1).join('.'), num[num.length-1] ].join(','));

#3


0  

str = "1.500.00";

var patt1=/.\d{2}$/;
var patt2=/\d{2}$/;
document.write(str.replace(str.match(patt1),','+str.match(patt2)));

result:

结果:

1.500,00

#4


0  

For text replace

用于文本替换

"I have 1.400.00$ and 57.60 pounds".replace(/\.(\d{2}\D?)/g, ",$1")

“我有1.400.00 $和57.60磅”.replace(/ \。(\ d {2} \ D?)/ g,“,$ 1”)

#1


2  

Use this:

用这个:

yourString.replace(/\.(\d\d)$/, ",$1");

#2


1  

How about not using a regexp:

如何不使用正则表达式:

var num = '1.500.00'.split('.'), 
    num1 = num.slice(0,num.length-1), 
    num2 = num[num.length-1];

alert(num1.join('.')+','+num2); //=> 1.500,00

Or without intermediate variables (num1, num2):

或者没有中间变量(num1,num2):

alert(num.slice(0,num.length-1).join('.')+','+num[num.length-1]); /=> 1.500,00

Or

要么

alert([ num.slice(0,num.length-1).join('.'), num[num.length-1] ].join(','));

#3


0  

str = "1.500.00";

var patt1=/.\d{2}$/;
var patt2=/\d{2}$/;
document.write(str.replace(str.match(patt1),','+str.match(patt2)));

result:

结果:

1.500,00

#4


0  

For text replace

用于文本替换

"I have 1.400.00$ and 57.60 pounds".replace(/\.(\d{2}\D?)/g, ",$1")

“我有1.400.00 $和57.60磅”.replace(/ \。(\ d {2} \ D?)/ g,“,$ 1”)