Encode/Decode javascript/C# strings

Date: 2019-10-28


Code:

/*
    Backspace is replaced with \b
    Newline is replaced with \n
    Tab is replaced with \t
    Carriage return is replaced with \r
    Form feed is replaced with \f
    Double quote is replaced with \"
    Backslash is replaced with \\
*/
const $ = document.querySelector.bind(document);
const on = (e, evt, fn) => e.addEventListener(evt, fn);
let quote = '"';

const encodeR = {
	"\b": "\\b",
	"\n": "\\n",
	"\t": "\\t",
	"\r": "\\r",
	"\f": "\\f",
	"\"": "\\\"",
	"\\": "\\\\",
};
const decodeR = {
	"\\b": "\b",
	"\\n": "\n",
	"\\t": "\t",
	"\\r": "\r",
	"\\f": "\f",
	"\\\"": "\"",
	"\\\\": "\\" 
};

const switchQuote = () => {
    const useSingleQuote = $("#chkSingleQuote").checked;
    quote = useSingleQuote ? "'" : '"';

    if (quote === "'") {
        encodeR["\'"] = "\\\'";
        delete encodeR["\""];
        decodeR["\\\'"] = "\'";
        delete decodeR["\\\""];
    } else {
        encodeR["\""] = "\\\"";
        delete encodeR["\'"];
        decodeR["\\\""] = "\"";
        delete decodeR["\\\'"];
    }
}

const encode = (text) => {
	let res = "";
	for (const c of String(text)) {
		if (c in encodeR) {
			res += encodeR[c];
		} else {
			res += c;
		}
	}
	return res;
};

const decode = (text) => {
	return String(text).replace(/(\\.)/gm, (group) => {
		if (group in decodeR) {
			return decodeR[group];
		}
		return group;
	});
};

const buildString = (text) => {
	var lines = text.split('\n');
	return lines
	.map(l => '\t' + quote + encode(l) + quote)
	.join(",\n");
};

// reverse buildstring
const stringPart = /"(.*?[^\\])"/gm;
const stringPartSq = /'(.*?[^\\])'/gm;
const getMatches = (re, str) => {
    let match, matches = [];
    while (match = re.exec(str)) {
        matches.push(match);
    }
    return matches;
};

const reverseBuildString = (text) => {
    const regEx = quote === "'" ? stringPartSq : stringPart;
    const lines = text.split('\n');
    const resultLines = [];
    for(const line of lines) 
    {
        const str = getMatches(regEx, line).map(m => decode(m[1])).join("").trim();
        if(str.length > 0) resultLines.push(str);
    }
    return resultLines.join("\n");
};

function copyStringToClipboard(string) {
    function handler(event) {
        event.clipboardData.setData('text/plain', string);
        event.preventDefault();
        document.removeEventListener('copy', handler, true);
    }
    document.addEventListener('copy', handler, true);
    document.execCommand('copy');
}

on(window, "DOMContentLoaded", () => {
	const input = $("#input");
	const output = $("#output");
	
	function run(fn) {
		return () => {
			switchQuote();
			output.value = fn();
			copyStringToClipboard(output.value);
		};
	}
	
	$("#btnEncode").addEventListener("click", run(() => encode(input.value)));
	$("#btnDecode").addEventListener("click", run(() => decode(input.value)));
	const prefix = "var sql = string.Join(Environment.NewLine, new string[] {\n";
	const postfix = "\n});";
    $("#btnBuildString").addEventListener("click", run(() => prefix + buildString(input.value) + postfix));
    $("#btnReverseBuildString").addEventListener("click", run(() => reverseBuildString(input.value)));
});
27400cookie-checkEncode/Decode javascript/C# strings