Web3JS – How to Remove Trailing Zero from web3.toAscii() Conversion

javascripttestingtruffleweb3js

I have a contract that returns a bytes32 type variable and I'm currently testing it with truffle and javascript.
The original data

['Roberto', 'Juan', 'Andrea']

This array is what i get as a response from my contract:

[ '0x526f626572746f00000000000000000000000000000000000000000000000000',
  '0x4a75616e00000000000000000000000000000000000000000000000000000000',
  '0x416e647265610000000000000000000000000000000000000000000000000000' ]

And this my code

let cands = [];
let length = Number(await voting.candidateListLength());
for (let i = 0; i < length; i++)
    cands.push(web3.toAscii(await voting.candidateList(i)));
console.log(cands);

Using web3.toAscii() method on each element to a obtain a human-friendly string produces the following:

[ 'Roberto\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000',
  'Juan\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000',
  'Andrea\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000' ]

Is there a way to remove the extra characters that come along with the original data?

Best Answer

web3.toUtf8() will do the magic for you

Related Topic