All files / src escaping.js

100% Statements 26/26
100% Branches 9/9
100% Functions 1/1
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 272x 2x 2x 2x 2x 2x 2x 2x 2x 14598x 14598x 14598x 14598x 14598x 14598x 14598x 14598x 14598x 131x 131x 131x 131x 131x 14598x 14598x 14598x  
const ATTR_REGEX = /[&"<]/g;
const CONTENT_REGEX = /[&<]/g;
 
/**
 * @template V
 * @param {V} value
 * @param {boolean} [is_attr]
 */
export function escape_html(value, is_attr) {
	const str = String(value ?? '');
 
	const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
	pattern.lastIndex = 0;
 
	let escaped = '';
	let last = 0;
 
	while (pattern.test(str)) {
		const i = pattern.lastIndex - 1;
		const ch = str[i];
		escaped += str.substring(last, i) + (ch === '&' ? '&amp;' : ch === '"' ? '&quot;' : '&lt;');
		last = i + 1;
	}
 
	return escaped + str.substring(last);
}