JavaScript:根据UTF-8值创建字符串或char [英] JavaScript: create a string or char from an UTF-8 value
本文介绍了JavaScript:根据UTF-8值创建字符串或char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与与此相同的问题,但是使用UTF-8而不是ASCII
Same question as this, but with UTF-8 instead of ASCII
在JavaScript中,如何获取UTF-8值的字符串表示形式?
In JavaScript, how can you get a string representation of a UTF-8 value?
例如如何将"c385"转换为Å"?
e.g. how to turn "c385" into "Å" ?
或如何将"E28093"转换为"—"(破折号)?
or how to turn "E28093" into "—" (m dash) ?
或如何将"E282AC"转换为€"(欧元符号)?
or how to turn "E282AC" into "€" (euro sign) ?
我的问题不是 Hex2Asc 的重复项>.您可以自己看到:hex2a("E282AC")会将字符串转换为â¬",而不是将其转换为€"(欧元符号)!
My question is NOT a duplicate of Hex2Asc. You can see for yourself: hex2a("E282AC") will transform the string into "â¬" instead of transforming it into "€" (euro sign) !!
推荐答案
我认为这可以满足您的要求:
I think this will do what you want:
function convertHexToString(input) {
// split input into groups of two
var hex = input.match(/[\s\S]{2}/g) || [];
var output = '';
// build a hex-encoded representation of your string
for (var i = 0, j = hex.length; i < j; i++) {
output += '%' + ('0' + hex[i]).slice(-2);
}
// decode it using this trick
output = decodeURIComponent(output);
return output;
}
console.log("'" + convertHexToString('c385') + "'"); // => 'Å'
console.log("'" + convertHexToString('E28093') + "'"); // => '–'
console.log("'" + convertHexToString('E282AC') + "'"); // => '€'
DEMO
积分:
- 将字符串拆分为段长n个字符
- 将整数数组转换为JavaScript字符串
- Javascript elegant way to split string into segments n characters long
- Convert integer array to string at javascript
- https://stackoverflow.com/a/14028246/74757
这篇关于JavaScript:根据UTF-8值创建字符串或char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文