Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing commas with dot and dot with commas

I am trying to replace all dots for comma and commas for dots and was wondering what is the best practice for doing this. If I do it sequentially, then the steps will overwrite each other.

For example: 1,234.56 (after replacing commas) --> 1.234.56 (after replacing dots) --> 1,234,56

Which is obviously not what I want.

One option I guess is splitting on the characters and joining afterwards using the opposite character. Is there an easier/better way to do this?

like image 597
Tim Lim Avatar asked Jul 25 '14 20:07

Tim Lim


3 Answers

You could use a callback

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

FIDDLE

If you're going to replace more than two characters, you could create a convenience function using a map to do the replacements

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

like image 122
adeneo Avatar answered Nov 14 '22 18:11

adeneo


You could do the following:

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

Working Demo

like image 13
hwnd Avatar answered Nov 14 '22 17:11

hwnd


Do it in stages using placeholder text:

var foo = '1,234.56';
foo = foo
    .replace(',', '~comma~')
    .replace('.', '~dot~')
    .replace('~comma~', '.')
    .replace('~dot~', ',')
like image 3
elixenide Avatar answered Nov 14 '22 18:11

elixenide