From 12a03b54bd54aabcfbf85cd9a3b5c3a01bf87c39 Mon Sep 17 00:00:00 2001 From: Ashley //// Date: Thu, 11 Apr 2024 08:19:08 +0000 Subject: [PATCH] add escapeHtml --- src/libpoketube/ptutils/libpt-coreutils.js | 73 ++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/src/libpoketube/ptutils/libpt-coreutils.js b/src/libpoketube/ptutils/libpt-coreutils.js index e4a9e853..46ed8e11 100644 --- a/src/libpoketube/ptutils/libpt-coreutils.js +++ b/src/libpoketube/ptutils/libpt-coreutils.js @@ -12,6 +12,78 @@ */ +/** + * Escapes special characters in the given string of text and replaces newline characters with
. + * + * @param {string} string The string to escape. + * @returns {string} The escaped string. + */ +function escapeHtml(string) { + /** + * Regular expression to match HTML special characters: ["'&<>] + * @type {RegExp} + */ + var matchHtmlRegExp = /["'&<>]/ + + /** + * Escapes special characters in the given string. + * @param {string} str The string to escape. + * @returns {string} The escaped string. + */ + function escapeString(str) { + var escape + var html = '' + var index = 0 + var lastIndex = 0 + + for (index = matchHtmlRegExp.exec(str).index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"' + break + case 38: // & + escape = '&' + break + case 39: // ' + escape = ''' + break + case 60: // < + escape = '<' + break + case 62: // > + escape = '>' + break + case 10: // Newline + escape = '
' + break + default: + continue + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index) + } + + lastIndex = index + 1 + html += escape + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html + } + + var str = '' + string + var match = matchHtmlRegExp.exec(str) + + if (!match) { + return str + } + + return escapeString(str) +} + + /** * Checks if a string is a valid JSON. * @param {string} str - The string to be checked. @@ -226,5 +298,6 @@ module.exports = { IsInArray, getRandomInt, capitalizeFirstLetter, + escapeHtml, turntomins };