前端实现native和ascii互转

NuoYI 2021年02月20日 57次浏览

native转ascii

const nativeToAscii = (content, ignoreNumeric, ignoreLetter) => {
	if(!content){
		return false;
	}
	content = content.split("");
	let ascii = "";
	for (let i = 0; i < content.length; i++) {
		let code = Number(content[i].charCodeAt(0));
		switch(code){
			case (!ignoreNumeric && code > 47 && code < 58)://0-9
			case (!ignoreLetter && code > 64 && code < 91)://A-Z
			case (!ignoreLetter && code > 96 && code < 123)://a-z
			case code > 127://Ascii表外字符
				let charAscii = code.toString(16);
				charAscii = new String("0000").substring(charAscii.length, 4) + charAscii;
				ascii += "\\u" + charAscii;
			break;
			default:
				ascii += content[i];
		}
	}
	return 
};

ascii转native

const asciiToNative = (content) => {
	if(!content){
		return false;
	}
	content = content.split("");
	let native = content[0];
	for (let i = 1; i < content.length; i++) {
		let code = content[i];
		native += String.fromCharCode(parseInt("0x" + code.substring(0, 4)));
		if (code.length > 4) {
			native += code.substring(4, code.length);
		}
	}
	return native;
};