t-comm
Version:
专业、稳定、纯粹的工具库
49 lines (47 loc) • 879 B
JavaScript
/**
* 获取字符串指定下标的 unicode
*
* @param {string} str - 字符串
* @param {number} index - unicode 的下标
* @returns {string} data
*
* @example
*
* unicodeAt('ABC', 1)
*
* // -> '\\u0042'
*
*/
function toUnicodeAt(str, index) {
if (index === void 0) {
index = 0;
}
var code = str.charCodeAt(index).toString(16).toUpperCase();
while (code.length < 4) {
code = "0".concat(code);
}
return "\\u".concat(code);
}
/**
* 获取字符串的 unicode
*
* @param {string} str - 字符串
* @returns {string} data
*
* @example
*
* toUnicode('ABC')
*
* // -> '\\u0041\\u0042\\u0043'
*
*
*/
function toUnicode(str) {
if (!str) {
return '';
}
return Array.prototype.reduce.call(str, function (pre, cur, index) {
return "".concat(pre).concat(toUnicodeAt(str, index));
}, '');
}
export { toUnicode, toUnicodeAt };