27

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

Thanks in advance,

Danny Fox
  • 35,333
  • 28
  • 67
  • 92
  • I am *sure* this is a duplicate... I wish the "related questions" were smarter about language tags :-/ –  Apr 23 '12 at 21:19
  • 1
    @ Danny: By "hex value," do you mean the **numeric** value FFFFFF hex (e.g., 16777215 decimal?). If so, just say "numeric value," putting the word "hex" in takes us into string land. I think you probably meant numeric, though. – T.J. Crowder Apr 23 '12 at 21:28
  • 1
    @T.J. Crowder I edited the title – Danny Fox Apr 23 '12 at 21:31
  • I have just answered a similar question here: https://stackoverflow.com/questions/48140695/best-way-to-convert-hex-string-with-hash-to-hex-value-with-0x-in-javascript/70607982#70607982 – 8urning8eard Jan 06 '22 at 13:43

2 Answers2

55

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));
Mike 'Pomax' Kamermans
  • 44,582
  • 14
  • 95
  • 135
Pointy
  • 389,373
  • 58
  • 564
  • 602
  • 2
    I would prefer `substring()` (as in @TJCrowder's answer) over `replace()`, for efficiency's sake. – Mark Reed Apr 23 '12 at 21:21
  • 1
    @MarkReed: It totally depends on what the OP *really* wants, which isn't clear from the question. It may be (given the lack of quotes on `0xFFFFFF`) that the OP wants then numeric value (which, of course, would make the title of the question completely wrong -- not the first time!). – T.J. Crowder Apr 23 '12 at 21:22
  • 1
    @TJCrowder: Your reply seems to be on the wrong answer. :) All I said above was that I would use `substring(1)` instead of `replace(regex)` for this problem. – Mark Reed Apr 23 '12 at 22:45
  • @Displee yes it does? – Pointy Aug 16 '17 at 22:46
  • @Pointy parseInt("#797e61".replace(/^#/, ''), 16); gives me 7962209 as result, and not 0x797e61. – Displee Aug 17 '17 at 00:25
  • @Displee of course, because the normal way to display numbers is in base 10, not base 16. – Pointy Aug 17 '17 at 00:35
0

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>
Garry Ho
  • 9
  • 1