JavaScript - calculate number values in a string

Paul125
Kilo Guru

Hello,

I am working on a script where I need a read an output and calculate the numbers at end of each line. I am trying the below script but I am unable make it further.

Note: script should be able to add values of 'Local Fixed disk' ONLY.

 

Output I get in the ecc queue:

Caption  Description       Size

C:       Local Fixed Disk  64422408192

D:       Local Fixed Disk  999645245440

G:       CD-ROM Disc       99884729

Script to read and calculate the size

//I pasted the above output in the Incident short descripion to make script running easier.
var gr = new GlideRecord('incident');
gr.get('number','INC7914138');
var output= gr.description;
var lines = output.split('\n');
var diskSpace = 0;
for (var i = 0; i < lines.length; i++)
	{
	var newArray = lines[i];
	
	if (newArray.indexOf('Local Fixed Disk'))
		{
		var n = newArray.split(" ");
		var disk = (n[n.length - 1]);
		diskSpace = diskSpace + parseInt(disk);
		gs.print(diskSpace);
		
	}
}

Expected output:

//addition
64422408192+999645245440 = 1064067653632

11 REPLIES 11

Paul, 

     The script below should do the trick:

 

var output = "Caption Description Size\n\nC: Local Fixed Disk 64422408192\n\nD: Local Fixed Disk 999645245440\n\nG: CD-ROM Disc 99884729";
var lines = output.split('\n');
var diskSpace = 0;


for(var i = 0; i < lines.length; i++) {
    var newArray = lines[i];
    if (newArray.indexOf('Local Fixed Disk') > -1) {
        var n = newArray.split(" ");
        var disk = (n[n.length - 1]);
        diskSpace = diskSpace + parseInt(disk);
    }
}
console.log(diskSpace);

Thanks, 

Derrick Johnson

//PUT the gs.print(diskSpace) out side of the for loop

 

for (var i = 0; i < lines.length; i++)
{
var newArray = lines[i];
//gs.info("newArray =" + i + " = " + newArray);
if (newArray.indexOf('Local Fixed Disk') > -1)
{
var n = newArray.split(" ");
var disk = (n[n.length-1]);

diskSpace = diskSpace + parseInt(disk);

}

gs.print(diskSpace);

Please mark Correct and click the Thumb up if my answer helps you resolve your issue. Thanks!
Vinod Kumar Kachineni
Community Rising Star 2022