文字列をUnicode(¥uxxx形式)へエスケープ

文字列をUnicode(¥uxxx形式)へエスケープするには、次の方法で可能です。

関数定義

JavaScript (ES5)

/**
 * 文字列をUnicode(¥uxxx形式)へエスケープ
 * @param {string} str 変換したい文字列
 * @return Unicode(¥uxxx形式)へエスケープした文字列を返す
 */
var unicodeEscape = function(str) {
	if (!String.prototype.repeat) {
		String.prototype.repeat = function(digit) {
			var result = '';
			for (var i = 0; i < Number(digit); i++) result += str;
			return result;
		};
	}

	var strs = str.split(''), hex, result = '';

	for (var i = 0, len = strs.length; i < len; i++) {
		hex = strs[i].charCodeAt(0).toString(16);
		result += '\\u' + ('0'.repeat(Math.abs(hex.length - 4))) + hex;
	}

	return result;
};

JavaScript (ES6以降)

/**
 * 文字列をUnicode(¥uxxx形式)へエスケープ
 * @param {string} str 変換したい文字列
 * @returns Unicode(¥uxxx形式)へエスケープした文字列を返す
 */
const unicodeEscape = str => str.split('').reduce((result, char) => {
	const hex = char.charCodeAt(0).toString(16);
	result += '\\u' + ('0'.repeat(Math.abs(hex.length - 4))) + hex;

	return result;
}, '');

使い方

引数

引数名 説明
第一引数
必須
str string 変換したい文字列

戻り値

変換された文字列を返します。

サンプルコード

JavaScript (ES5)

var result = unicodeEscape('abc123あいうえお');

alert(result);

JavaScript (ES6以降)

const result = unicodeEscape('abc123あいうえお');

console.log(result);

JavaScript逆引きリファレンス一覧へ戻る