v2
4/19/2024 by rich -00
Setup HTML - click to add setup HTML
disable setup JavaScript
Setup JavaScript
function get_escaped_char1(char) {
	switch (char) {
		case '"': return '\\"';
		case '<': return '\\u003C';
		case '\\': return '\\\\';
		case '\n': return '\\n';
		case '\r': return '\\r';
		case '\t': return '\\t';
		case '\b': return '\\b';
		case '\f': return '\\f';
		case '\u2028': return '\\u2028';
		case '\u2029': return '\\u2029';
		default:
			return char < ' '
				? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`
				: '';
	}
}

function stringify_string1(str) {
	let result = '';
	let last_pos = 0;
	const len = str.length;

	for (let i = 0; i < len; i += 1) {
		const char = str[i];
		const replacement = get_escaped_char1(char);
		if (replacement) {
			result += str.slice(last_pos, i) + replacement;
			last_pos = i + 1;
		}
	}

	return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
}

// -----

function get_escaped_char2(char) {
	switch (char) {
		case '"': return '\\"';
		case '<': return '\\u003C';
		case '\\': return '\\\\';
		case '\n': return '\\n';
		case '\r': return '\\r';
		case '\t': return '\\t';
		case '\b': return '\\b';
		case '\f': return '\\f';
		case '\u2028': return '\\u2028';
		case '\u2029': return '\\u2029';
		default:
			return char < ' '
				? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`
				: char;
	}
}

const reg = /["<\\\n\r\t\b\f\u2028\u2029\x00-\x1f]/g
function stringify_string2(str) {
	return reg.test(str) ? `"${str.replace(reg, get_escaped_char2)}"` : `"${str}"`;
}

// -----

const m = {
  '<': '\\u003C',
  '\u2028': '\\u2028',
  '\u2029': '\\u2029'
}
const preg = /[<\u2028\u2029]/g;
function stringify_string3(str) {
	return JSON.stringify(str).replace(preg, char => m[char]);
}

// -----


function stringify_string4(str) {
	return reg.test(str) ? JSON.stringify(str).replace(preg, char => m[char]) : `"${str}"`;
}

// -----

const tests = [
	'short',
	'<blah>',
	//'long'.repeat(1000),
	//'long2\n'.repeat(1000),
	//'"\n"'.repeat(1000),
	//'<'.repeat(1000),
	//'long'.repeat(1000) + '\n'
]; 
delete caserun single casemove downdrag and drop case


ready



for (const test of tests) {
	stringify_string4(test);
}
delete caserun single casemove upmove downdrag and drop case


ready



for (const test of tests) {
	stringify_string3(test);
}
delete caserun single casemove upmove downdrag and drop case


ready



for (const test of tests) {
	stringify_string2(test);
}
delete caserun single casemove updrag and drop case


ready



for (const test of tests) {
	stringify_string1(test);
}
Test Case - click to add another test case
Teardown JS - click to add teardown JavaScript
Output (DOM) - click to monitor output (DOM) while test is running
RUN