Created
August 3, 2018 17:30
-
-
Save quisido/b0e1ee720e0f88ba01b4970b46d25f66 to your computer and use it in GitHub Desktop.
PHP's htmlspecialchars implemented in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create the function. | |
var htmlspecialchars = function(string) { | |
// Our finalized string will start out as a copy of the initial string. | |
var escapedString = string; | |
// For each of the special characters, | |
var len = htmlspecialchars.specialchars.length; | |
for (var x = 0; x < len; x++) { | |
// Replace all instances of the special character with its entity. | |
escapedString = escapedString.replace( | |
new RegExp(htmlspecialchars.specialchars[x][0], 'g'), | |
htmlspecialchars.specialchars[x][1] | |
); | |
} | |
// Return the escaped string. | |
return escapedString; | |
}; | |
// A collection of special characters and their entities. | |
htmlspecialchars.specialchars = [ | |
[ '&', '&' ], | |
[ '<', '<' ], | |
[ '>', '>' ], | |
[ '"', '"' ] | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment