javascript 如何从JS中的字符串中获取十六进制整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10288445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:20:17 来源:igfitidea点击:
How to get hex integer from a string in JS?
提问by Danny Fox
I would like to convert this: "#FFFFFF"
to this: 0xFFFFFF
. How is it possible without using eval?
我想将 this: 转换"#FFFFFF"
为 this: 0xFFFFFF
。不使用eval怎么可能?
Thanks in advance,
提前致谢,
回答by Pointy
Strip off the "#" and use parseInt()
.
去掉“#”并使用parseInt()
.
var hex = parseInt(str.replace(/^#/, ''), 16);
Then, if you want to seeit in hex, you can use .toString()
:
然后,如果您想以十六进制查看它,可以使用.toString()
:
console.log(hex.toString(16));
回答by Garry Ho
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>