Reputation: 18875
I need to replace the decimal separator in a string, and the decimal separators could be a dot .
(e.g. English) or a comma ,
(e.g. German). So I have the variable sep
for containing the separator string.
To convert the English-based decimal separator, I do the following replacement, but I got ,dd,dd
rather than 120,dd
:
var sep = '.';
var numberStr = '120.31';
numberStr = numberStr.replace(new RegExp(sep + '\\d{2}', 'g'), ',dd');
console.log(numberStr);
Does anyone know where I went wrong?
Upvotes: 1
Views: 293
Reputation: 184
The dot-character in RegularExpressions matches one single character, regardless of the actual character itself (details depending on the programming language / regex engine / flags in use).
If you want to match a dot, your separator should escape the regex dot-selector character like var sep = '\\.';
to match an actual dot, not 'any single character'.
So your error occurs because in 120.31
the pattern [any character followed by 2 numbers]
is found/replaced twice, once for 120
and once for .31
, as 1
aswell as .
match the regex dot-selector '.'
.
For details see the Regex Cheat Sheet
Upvotes: 4
Reputation: 106385
You need to escape the separator (so that it'll be treated by RegExp engine as is) by prefixing it with \
character:
var escapedSep = sep.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
numberStr = numberStr.replace(new RegExp(escapedSep + '\\d{2}', 'g'), ',dd');
Otherwise .
is treated as a RegExp metacharacter, matching on any symbol (except line breaks).
Upvotes: 1