When I submit/POST data to the server, I need to HTMLencode its characters (the relevant ones), since disabling input check by setting validationRequest = false
is not a good practice.
All solutions are finally replacing chars in string:
This is what i've written.
function htmlEncode(str) {
str = str.replace(/\&/g, "&");
str = str.replace(/\</g, "<");
str = str.replace(/\>/g, ">");
str = str.replace(/ /g, " ");
return str;
}
But apprently regex could be replaced with something much faster (don't get me wrong - I love regex).
Also, working with indexes + sub-strings seems wasteful.
What is the fastest way of doing it?
function htmlEncode(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
jsperf tests show this method is fast and possibly the fastest option if you're in a recent browser version
anothre way to also like this
function htmlEncode(value){
return $('<div/>').text(value).html();
}
function htmlDecode(value){
return $('<div/>').html(value).text();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With