1
Fork 0

add escapeHtml

This commit is contained in:
Ashley //// 2024-04-11 08:19:08 +00:00
parent 9b7c097f2e
commit 12a03b54bd

View file

@ -12,6 +12,78 @@
*/
/**
* Escapes special characters in the given string of text and replaces newline characters with <br>.
*
* @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 = '&quot;'
break
case 38: // &
escape = '&amp;'
break
case 39: // '
escape = '&#39;'
break
case 60: // <
escape = '&lt;'
break
case 62: // >
escape = '&gt;'
break
case 10: // Newline
escape = '<br>'
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
};