Skip to content

Instantly share code, notes, and snippets.

@quisido
Created August 3, 2018 17:30
Show Gist options
  • Save quisido/b0e1ee720e0f88ba01b4970b46d25f66 to your computer and use it in GitHub Desktop.
Save quisido/b0e1ee720e0f88ba01b4970b46d25f66 to your computer and use it in GitHub Desktop.
PHP's htmlspecialchars implemented in JavaScript
// 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 = [
[ '&', '&amp;' ],
[ '<', '&lt;' ],
[ '>', '&gt;' ],
[ '"', '&quot;' ]
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment