Replacing commas with a dot and a comma

I am trying to replace all the semicolon and comma points with dots and wonder what is best suited for this. If I do this sequentially, the steps will overwrite each other.

For example: 1,234.56 (after replacing commas) → 1.234.56 (after replacing dots) → 1,234.56

This is obviously not what I want.

One option, I think, is broken up into characters and then connected using the opposite character. Is there an easier / better way to do this?

+6
source share
5 answers

You can use callback

"1,234.56".replace(/[.,]/g, function(x) { return x == ',' ? '.' : ','; }); 

Fiddle

If you intend to replace more than two characters, you can create a convenient function using the card to replace

 function swap(str, swaps) { var reg = new RegExp('['+Object.keys(swaps).join('')+']','g'); return str.replace(reg, function(x) { return swaps[x] }); } var map = { '.':',', ',':'.' } var result = swap("1,234.56", map); // 1.234,56 

Fiddle

+13
source

You can do the following:

 var str = '1,234.56'; var map = {',':'.','.':','}; str = str.replace(/[,.]/g, function(k) { return map[k]; }); 

Working demo

+11
source

Do this step by step using the placeholder text:

 var foo = '1,234.56'; foo = foo .replace(',', '~comma~') .replace('.', '~dot~') .replace('~comma~', '.') .replace('~dot~', ',') 
+3
source

You can use the for loop. Sort of:

 var txt = document.getElementById("txt"); var newStr = ""; for (var i = 0; i < txt.innerHTML.length; i++){ var char = txt.innerHTML.charAt(i); if (char == "."){ char = ","; }else if (char == ","){ char = "."; } newStr += char; } txt.innerHTML = newStr; 

Here's the fiddle: http://jsfiddle.net/AyLQt/1/

I must say that @adenoeo's answer is smoother: D

+2
source

In javascript you can use

 var value = '1.000.000,55'; var splitValue = value.split('.'); for (var i = 0; i < splitValue.length; i++) { var valPart = splitValue[i]; var newValPart = valPart.replace(',', '.'); splitValue[i] = newValPart; } var newValue = splitValue.join(','); console.log(newValue); 
0
source

Source: https://habr.com/ru/post/972857/


All Articles