0

I have a string "000-2.50" or "00-12.50" or "0-120.50" and I want to replace the zeros up to the minus sign "-" with an @ char.

I want to end up with "@@@-2.50" or "@@-12.50" or "@-120.50". How do I achieve that using Regex?

revo
  • 43,830
  • 14
  • 67
  • 109
Pat
  • 41
  • 5
  • 3
    regex by itself doesnt replace at all. which language you are working with? – guijob Mar 03 '18 at 15:31
  • 1
    Tell us what language/tool you are using, and also do the zeroes to be replaced always start at the beginning of the string? – Tim Biegeleisen Mar 03 '18 at 15:38
  • Tell us what language/tool you are using, and also do the zeroes to be replaced always start at the beginning of the string? – Tim Biegeleisen Mar 03 '18 at 15:38
  • I am using JavaScript. and also do the zeroes to be replaced always start at the beginning of the string? - YES – Pat Mar 03 '18 at 15:45

2 Answers2

1

Look for all zeros that are followed by a dash using a positive lookahead:

Method 1:

0(?=[^-]*-)

JS Code:

console.log(
  "000-2.50".replace(/0(?=[^-]*-)/g, "@")
);

Method 2

Or if you only want leading zeros:

console.log(
  "000-2.50".replace(/^0+(?=-)/g, function(match) {
      return "@".repeat(match.length);
  })
)
revo
  • 43,830
  • 14
  • 67
  • 109
0

To replace each 0 from beginning of the string, how about using the sticky flag y

var str = '000-2.50';

var res = str.replace(/0/gy, '@');

console.log(res);
bobble bubble
  • 11,968
  • 2
  • 22
  • 34