How to Get Hex Integer from a String in Js?

I would like to convert this: "#FFFFFF" to this: 0xFFFFFF. How is it possible without using eval?

Thanks in advance,

4

3 Answers

Strip off the "#" and use parseInt().

var hex = parseInt(str.replace(/^#/, ''), 16);

Then, if you want to see it in hex, you can use .toString():

console.log(hex.toString(16));
6

Use this code:

var resultP = document.getElementById('result');
var btn = document.querySelector('button');
var input = document.querySelector('input');
function convert(hex) {
  return Number(`0x${hex.substr(1)}`);
}
btn.addEventListener('click', () => {
  resultP.innerHTML = convert(input.value);
})
* {
  font-family: Arial;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Hex code to hex integer</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <input type="text" maxlength="7" />
    <button>Done</button>
    <br />
    Result:
    <p id="result"></p>
  </body>
</html>
1

You could try this code:

function hex2num(hexcode){ return Number(  '0x' + hexcode.split(/[^0-9a-fA-F]+/).join('')  ) }

This function will strip out all characters that are not numbers between 0-9 or alphabetical characters between A-F before trying to parse the input. The output is a number, because 0x009 === 9 in JS.

This solution works when dealing with numbers that are less than the MAX SAFE INTEGER (9007199254740991) but if the hex code equates to a number larger than that you will probably need to use a different solution.

Expected Usage:

  • hex2num('#0000FF') === 255 // true
  • hex2num('#FFFFFF') === 16777215 // true
  • hex2num('0x000000000001') === 1 // true
  • hex2num('0L0L4') === 4 // true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest