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 };