Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to replace string in js?

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, "&lt;");
    str = str.replace(/\>/g, "&gt;");
    str = str.replace(/ /g, "&nbsp;");
    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?

like image 880
Royi Namir Avatar asked Sep 24 '12 09:09

Royi Namir


Video Answer


1 Answers

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

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();
}
like image 199
Sender Avatar answered Sep 28 '22 09:09

Sender