在 JavaScript 中,可以使用 charCodeAt()
方法将字符串中的每个字符转换为其对应的 Unicode 数字编码。
示例代码:
const str = "__conf__";
const numericRepresentation = Array.from(str).map(char => char.charCodeAt(0));
console.log(numericRepresentation);
// 输出: [95, 95, 99, 111, 110, 102, 95, 95]
解释:
Array.from(str)
→["_", "_", "c", "o", "n", "f", "_", "_"]
.map(char => char.charCodeAt(0))
→
"_"
→95
(Unicode)
"c"
→99
,"o"
→111
, …
如果需要拼接成连续数字字符串:
const numericString = Array.from(str).map(c => c.charCodeAt(0)).join('');
console.log(numericString); // "9595991111101029595"
反向解析(数字转回字符串):
const numbers = [95, 95, 99, 111, 110, 102, 95, 95];
const originalStr = String.fromCharCode(...numbers);
console.log(originalStr); // "__conf__"
适用于需要隐藏或编码特定字符串的场景。
内容由零声教学AI助手提供,问题来源于学员提问