1

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?

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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).

2 Comments

To clarify on this ... (he answered before I could do), the regex ended on .\d{2} which means that the dot matches everything. To escape the dot, you have to add \\ so that a dot is presented, not "matches everything except line breaks". But I should look to basst314's answer. Reason: those additional regex. That's uncalled for.
If you check my original answer, you see that was the first version. But did you think what happens when OP changes a separator?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.