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

2

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

For completeness and legacy sake: .replace(/:/g, '')
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));

Comments

-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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.