Reputation: 411
I thought it was very simple to find out. But how many ways I tried still not work properly. Below is the test snippet.
"100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)".replace(/[\.,\d]*/g, '{n}')
And I want the result like below.
{n}$ and {n}EUR {n}USD {n}$ ({n})
Upvotes: 0
Views: 51
Reputation: 67968
\.?\d[^\s]*\d
Try this.Replace with {n}
.See demo.
http://regex101.com/r/kP8uF5/3
var re = /\.?\d[^\s]*\d/gm;
var str = '100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)';
var subst = '{n}';
var result = str.replace(re, subst);
Upvotes: 0
Reputation: 51330
The problem here is that [\.,\d]*
can match an empty string. The first step would be to use [.,\d]+
so that at least one of these characters matches.
But a better regex would be \d[.,\d]*
because it ensures the replaced characters begin with a digit, so it won't replace periods in sentences.
If you want to go further, you can also use (?=[.,\d]*\d)[.,\d]+
if to handle numbers starting with periods. This one would be the proper answer for your case. The lookahead ensures there's at least one digit anywhere in the replaced text.
Note that you don't need to escape the .
inside a character class.
Upvotes: 1
Reputation: 1482
The *
is your problem, change the regex to /[.,\d]+/g
instead.
"100$ and 1.000,000EUR 1,00.0.000USD .90000000000000000000$ (09898)".replace(/[.,\d]+/g, '{n}');
Output
{n}$ and {n}EUR {n}USD {n}$ ({n})
JSFiddle Example Check console screen for the output.
Upvotes: 1