Skip to content

Commit

Permalink
Utils: faster escaping functions (see issue #327)
Browse files Browse the repository at this point in the history
  • Loading branch information
miripiruni committed Sep 6, 2016
1 parent d53646f commit 3e80b00
Showing 1 changed file with 119 additions and 13 deletions.
132 changes: 119 additions & 13 deletions lib/bemxjst/utils.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,124 @@
exports.xmlEscape = function(str) {
return (str + '')
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
var amp = '&amp;';
var lt = '&lt;';
var gt = '&gt;';
var quot = '&quot;';
var singleQuot = '&#39;';

var matchXmlRegExp = /[&<>]/;

exports.xmlEscape = function(string) {
var str = '' + string;
var match = matchXmlRegExp.exec(str);

if (!match)
return str;

var escape;
var html = '';
var index = 0;
var lastIndex = 0;

for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 38: // &
escape = amp;
break;
case 60: // <
escape = lt;
break;
case 62: // >
escape = gt;
break;
default:
continue;
}

if (lastIndex !== index)
html += str.substring(lastIndex, index);

lastIndex = index + 1;
html += escape;
}

return lastIndex !== index ?
html + str.substring(lastIndex, index) :
html;
};
exports.attrEscape = function(str) {
return (str + '')
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;');

var matchAttrRegExp = /["&]/;

exports.attrEscape = function(string) {
var str = '' + string;
var match = matchAttrRegExp.exec(str);

if (!match)
return str;

var escape;
var html = '';
var index = 0;
var lastIndex = 0;

for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = quot;
break;
case 38: // &
escape = amp;
break;
default:
continue;
}

if (lastIndex !== index)
html += str.substring(lastIndex, index);

lastIndex = index + 1;
html += escape;
}

return lastIndex !== index ?
html + str.substring(lastIndex, index) :
html;
};
exports.jsAttrEscape = function(str) {
return (str + '')
.replace(/&/g, '&amp;')
.replace(/'/g, '&#39;');

var matchJsAttrRegExp = /['&]/;

exports.jsAttrEscape = function(string) {
var str = '' + string;
var match = matchJsAttrRegExp.exec(str);

if (!match)
return str;

var escape;
var html = '';
var index = 0;
var lastIndex = 0;

for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 38: // &
escape = amp;
break;
case 39: // '
escape = singleQuot;
break;
default:
continue;
}

if (lastIndex !== index)
html += str.substring(lastIndex, index);

lastIndex = index + 1;
html += escape;
}

return lastIndex !== index ?
html + str.substring(lastIndex, index) :
html;
};

exports.extend = function extend(o1, o2) {
Expand Down

0 comments on commit 3e80b00

Please sign in to comment.