1

--html--

<table>
<tr>
<th>a</th>
<th>b<th>
</tr>
<tbody class = "tabledata">
<tr>a</tr>
<tr>b</tr>
</tbody>
</table>

--jquery--

 $('.tabledata').empty();
for (var i = 0; i < result.length; i++) {
                var abc = '<tr><td>' + result[i]['a'] + '</td><td>' + result[i]['b'] + '</td></tr>'
                //var results = abc.replace(/-(.*)/, "()");

                $('.tabledata').append(abc);
}

the result carries negetive values such as -245.1, -897.7. I want to change them as (245.1) and (897.7). I have tried .replace function but could not get it work.

LaMars
  • 45
  • 2
  • 10

1 Answers1

3

You can use Math.abs while creating the abc itself

var a  = "(" + Math.abs( result[i]['a'] ) + ")";
var b  = "(" + Math.abs( result[i]['b'] ) + ")";
var abc = '<tr><td>' + a + '</td><td>' + b + '</td></tr>'

Or do some refactoring to make the code less verbose

var fnAbs = ( s ) => "(" + Math.abs( s ) + ")";
var abc = '<tr><td>' + fnAbs( result[i]['a'] ) + '</td><td>' + fnAbs( result[i]['b'] )  + '</td></tr>';

if you don't want to wrap non-negative values with () then change fnAbs as

var fnAbs = ( s ) => +s < 0 ? "(" + Math.abs( s ) + ")" : s;

Note

+s < 0, converts s to Number before comparison in case s is of type "string"

gurvinder372
  • 66,980
  • 10
  • 72
  • 94