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?
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?
Look for all zeros that are followed by a dash using a positive lookahead:
0(?=[^-]*-)
JS Code:
console.log(
"000-2.50".replace(/0(?=[^-]*-)/g, "@")
);
Or if you only want leading zeros:
console.log(
"000-2.50".replace(/^0+(?=-)/g, function(match) {
return "@".repeat(match.length);
})
)
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);