From e58d65822a18a7d04b4b7a3171e51f6f9a6732d7 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Thu, 19 Nov 2020 23:04:40 -0500 Subject: [PATCH] simplify --- src/runtime/internal/ssr.ts | 48 +++++++++++++------------------------ 1 file changed, 17 insertions(+), 31 deletions(-) diff --git a/src/runtime/internal/ssr.ts b/src/runtime/internal/ssr.ts index 022fb67ddb..51e8fc6f4c 100644 --- a/src/runtime/internal/ssr.ts +++ b/src/runtime/internal/ssr.ts @@ -32,45 +32,31 @@ export function spread(args, classes_to_add) { return str; } -const ATTR_REGEX = /[&<"]/; -const CONTENT_REGEX = /[&<]/; +const ATTR_REGEX = /[&"]/g; +const CONTENT_REGEX = /[&<]/g; + +const escapes = { + '"': '"', + '&': '&', + '<': '<' +}; export function escape(html: string, attr: 0 | 1 = 0) { if (typeof html !== 'string') return html; - const match = (attr ? ATTR_REGEX : CONTENT_REGEX).exec(html); - if (!match) return html; - - let index = 0; - let lastIndex = 0; - let out = ''; - let escape = ''; - - for (index = match.index; index < html.length; index++) { - switch (html.charCodeAt(index)) { - case 34: // " - if (!attr) continue; - escape = '"'; - break; - case 38: // & - escape = '&'; - break; - case 60: // < - escape = '<'; - break; - default: - continue; - } + const pattern = (attr ? ATTR_REGEX : CONTENT_REGEX); + pattern.lastIndex = 0; - if (lastIndex !== index) { - out += html.substring(lastIndex, index); - } + let escaped = ''; + let last = 0; - lastIndex = index + 1; - out += escape; + while (pattern.test(html)) { + const i = pattern.lastIndex - 1; + escaped += html.slice(last, i) + escapes[html[i]]; + last = i + 1; } - return lastIndex !== index ? out + html.substring(lastIndex, index) : out; + return escaped + html.slice(last); } export function each(items, fn) {