mirror of
https://codeberg.org/ashley/poke.git
synced 2024-11-26 00:38:54 +01:00
add escapeHtml
This commit is contained in:
parent
9b7c097f2e
commit
12a03b54bd
1 changed files with 73 additions and 0 deletions
|
@ -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 = '"'
|
||||
break
|
||||
case 38: // &
|
||||
escape = '&'
|
||||
break
|
||||
case 39: // '
|
||||
escape = '''
|
||||
break
|
||||
case 60: // <
|
||||
escape = '<'
|
||||
break
|
||||
case 62: // >
|
||||
escape = '>'
|
||||
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
|
||||
};
|
||||
|
|
Loading…
Reference in a new issue