Editing html encode This edit will create a new revision. Your details (optional) Name Email (won’t be displayed; might be used for Gravatar) URL Test case details Title * Published (uncheck if you want to fiddle around before making the page public) Description (in case you feel further explanation is needed)(Markdown syntax is allowed) Speed test escaping html characters with if statements and regular expressions. Are you a spammer? (just answer the question) Preparation code Preparation code HTML (this will be inserted in the <body> of a valid HTML5 document in standards mode) (useful when testing DOM operations or including libraries) Include JavaScript libraries as follows: <script src="//cdn.ext/library.js"></script> Define setup for all tests (variables, functions, arrays or other objects that will be used in the tests) (runs before each clocked test loop, outside of the timed code region) (e.g. define local test variables, reset global variables, clear canvas, etc.) (see FAQ) function encodeWithIfs(str) { var result = "" for (var cc = 0; cc < str.length; cc++) { var c = str.charAt(cc) if (c == "&") result += '&' else if (c == '"') result += '"' else if (c == "'") result += ''' else if (c == "<") result += '<' else if (c == ">") result += '>' else result += c } return result } function endcodeWithRegEx(str) { return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>') } function endcodeWithRegEx2(str) { return str.replace(/[&<>"'`]/g, function(chr) { return '&#' + chr.charCodeAt(0) + ';' }) } function doEncode(func) { var a = func("<div></div>") var b = func("This is a string with no replacements") var c = func("All replacement chars & \" ' < >") } var goog_string_amperRe_ = /&/g; var goog_string_ltRe_ = /</g; var goog_string_gtRe_ = />/g; var goog_string_quotRe_ = /\"/g; var goog_string_allRe_ = /[&<>\"]/; function goog_string_htmlEscape(str) { // quick test helps in the case when there are no chars to replace, in // worst case this makes barely a difference to the time taken if (!goog_string_allRe_.test(str)) return str; // str.indexOf is faster than regex.test in this case if (str.indexOf('&') != -1) { str = str.replace(goog_string_amperRe_, '&'); } if (str.indexOf('<') != -1) { str = str.replace(goog_string_ltRe_, '<'); } if (str.indexOf('>') != -1) { str = str.replace(goog_string_gtRe_, '>'); } if (str.indexOf('"') != -1) { str = str.replace(goog_string_quotRe_, '"'); } return str; } Define teardown for all tests (runs after each clocked test loop, outside of the timed code region) (see FAQ) Code snippets to compare Test 1 Title Async (check if this is an asynchronous test) Code doEncode(encodeWithIfs) Test 2 Title Async (check if this is an asynchronous test) Code doEncode(endcodeWithRegEx) Test 3 Title Async (check if this is an asynchronous test) Code doEncode(endcodeWithRegEx2) Test 4 Title Async (check if this is an asynchronous test) Code doEncode(goog_string_htmlEscape)