JQUERY replaces negative integer in parentheses

I have this line

var string = "-200000";

      

and i converted string

with coma thousand separator with this regex

var results = string.replace(/\B(?=(\d{3})+\b)/g, ",");

      

therefore it becomes -200,000

. The question is how to change the negative sign to parentheses, i.e. (200,000)

...

Thank!

+3


source to share


1 answer


Just add .replace(/-(.*)/, "($1)");

. Since the replacement will not hit if there is no match, the positive numbers remain as they are and the negative numbers are replaced - with ()



var results = string.replace(/\B(?=(\d{3})+\b)/g, ",").replace(/-(.*)/, "($1)");

      

+3


source







All Articles