Encode/Decode javascript/C# strings

   


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);
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;
    return getMatches(regEx, text)
        .map(m => decode(m[1]))
        .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');
}

window.addEventListener("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)));
});