Fastest way to replace string in js?

When I send / POST data to the server, I need HTMLencode characters (corresponding), since disabling input validation by setting validationRequest = falseis not a good practice.

All solutions finally replace the characters in the string:

This is what I wrote.

function htmlEncode(str) {
    str = str.replace(/\&/g, "&");
    str = str.replace(/\</g, "&lt;");
    str = str.replace(/\>/g, "&gt;");
    str = str.replace(/ /g, "&nbsp;");
    return str;
}

But perhaps the regular expression can be replaced with something much faster (don't get me wrong - I love the regular expression).

Also, working with indexes + substrings seems wasteful.

What is the fastest way to do this?

+5
source share
3 answers
function htmlEncode(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

jsperf , , ,

anothre

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}
+7

HTML, :

function htmlEncode(str) {
    var d = document.createElement('b');
    d.innerText = str;
    return d.innerHTML;
}

. , regExp : http://jsperf.com/encodehtml

, -, , HTML .

innerText , . RegExp , - , , HTML RegExp .

0
function htmlEncode(value){
    if (value) {
        return jQuery('<div />').text(value).html();
    } else {
        return '';
    }
}

function htmlDecode(value) {
    if (value) {
        return $('<div />').html(value).text();
    } else {
        return '';
    }
}
0

All Articles