Reputation: 15
I have a string:
var string = {fld_1}-1000-{fld_1}
and I need to add {} around the digits 1000 (could be any number of digits though).
So the end string would be:
{fld_1}-{1000}-{fld_1}
My current regex is this:
var result = string.replace(/-(\d+)/g, '{$1}');
But I end up with this:
{fld_1}{1000}{1000}-{fld_1}
This is for a javscript application
Edit:
I should have noted that the strings could be this as well:
{fld_1}/1000-{fld_1}
or
{fld_1}+1000/{fld_1}
Upvotes: 1
Views: 3641
Reputation: 173562
Since \d
is part of \w
and [_+-]
is not, you can use the word boundary assertion \b
to your advantage:
'{fld_1}-1000-{fld_1}'.replace(/\b(\d+)\b/g, '{$1}')
Note that fld_1
is not replaced here, because _
is part of \w
and as such there's no transition from \W
to \w
or vice versa.
Upvotes: 1