1

I tried a lot of ways, but none give the expected result.

Input: 04:3d:54:a2:68:61:80

Expected output: 01193333618139520

How would I go about this in JS?

const value = `04:3d:54:a2:68:61:80`
const barcode = parseInt(value.replace(':', ''), 16)
console.log(barcode) // 1085
Titus
  • 22,031
  • 1
  • 23
  • 33
Travinns
  • 263
  • 1
  • 3
  • 13
  • 1
    please make an attempt and share [mcve] before asking for help. – depperm Jan 13 '23 at 15:07
  • [how-do-i-replace-all-occurrences-of-a-string-in-javascript](https://stackoverflow.com/questions/1144783/how-do-i-replace-all-occurrences-of-a-string-in-javascript), also someone has to mention, that you are barely below `Number.MAX_SAFE_INTEGER`, at 51 bits. If your input would start with `2` instead of `0`, that would already cause issues. – ASDFGerte Jan 13 '23 at 15:36

3 Answers3

3

The problem is that you are using replace instead of replaceAll

const value = `04:3d:54:a2:68:61:80`
const barcode = parseInt(value.replaceAll(':', ''), 16)
console.log(barcode)

As Lian suggests, you can also achieve that with replace(/:/g, '')

And therefore get better browser compatibility

const value = `04:3d:54:a2:68:61:80`
const barcode = parseInt(value.replace(/:/g, ''), 16)
console.log(barcode)
Yedidya Rashi
  • 1,012
  • 8
  • 18
1

First remove colons, then use parseInt(myHex, 16).

const myHex = '04:3d:54:a2:68:61:80';

function hexToDecimal(hexadecimal) {
  return parseInt(hexadecimal.replaceAll(':', ''), 16);
}

console.log(hexToDecimal(myHex));
korlend
  • 41
  • 2
-1

Use the parseInt function, passing your input as the first parameter and 16 (since hexadecimal is base-16) as the second.

let input = '04:3d:54:a2:68:61:80';
const inputParsed = parseInt(input.replace(/:/g, ''), 16); // 1193333618139520

If you need the leading zero for some reason you can do something like this:

const inputParsedStr = `${inputParsed.toString().startsWith('0') ? '' : '0'}${inputParsed}`; // '01193333618139520'
SeaJay76
  • 1
  • 2