From bc7b8e2f890e079557c0a3d04059cd42600d0562 Mon Sep 17 00:00:00 2001 From: Vitaly Puzrin Date: Sun, 26 Oct 2014 07:24:26 +0300 Subject: [PATCH] Perf: regex opts --- README.md | 2 +- lib/common/utils.js | 21 +++++++++++++++------ lib/parser_block.js | 13 +++++++------ 3 files changed, 23 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 617d96d..f98f7fb 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ var md = new Remarkable('full'); By default remarkable is configured to be similar to GFM, but with disabled HTML. -### Highligh fenced blocks +### Highlight fenced blocks To highlight content of fenced block, assing function to `highlight` option: diff --git a/lib/common/utils.js b/lib/common/utils.js index 58d6d0e..4eb7901 100644 --- a/lib/common/utils.js +++ b/lib/common/utils.js @@ -30,18 +30,27 @@ function assign(obj /*from1, from2, from3, ...*/) { } -var ESCAPE_TEST_RE = /[&<>"]/; +var HTML_ESCAPE_TEST_RE = /[&<>"]/; +var HTML_ESCAPE_REPLACE_RE = /[&<>"]/g; +var HTML_REPLACEMENTS = { + '&': '&', + '<': '<', + '>': '>', + '"': '"' +}; + +function replaceUnsafeChar(ch) { + return HTML_REPLACEMENTS[ch]; +} function escapeHtml(str) { - if (ESCAPE_TEST_RE.test(str)) { - if (str.indexOf('&') >= 0) { str = str.replace(/&/g, '&'); } - if (str.indexOf('<') >= 0) { str = str.replace(/') >= 0) { str = str.replace(/>/g, '>'); } - if (str.indexOf('"') >= 0) { str = str.replace(/"/g, '"'); } + if (HTML_ESCAPE_TEST_RE.test(str)) { + return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar); } return str; } + var UNESCAPE_MD_RE = /\\([\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-])/g; function unescapeMd(str) { diff --git a/lib/parser_block.js b/lib/parser_block.js index 7c4d6cc..d750557 100644 --- a/lib/parser_block.js +++ b/lib/parser_block.js @@ -104,23 +104,24 @@ ParserBlock.prototype.tokenize = function (state, startLine, endLine) { } }; +var TABS_SCAN_RE = /[\n\t]/g; +var NEWLINES_RE = /\r[\n\u0085]|[\u2424\u2028\u0085]/g; +var SPACES_RE = /\u00a0/g; ParserBlock.prototype.parse = function (src, options, env) { var state, lineStart = 0, lastTabPos = 0; - if (!src) { return ''; } + if (!src) { return []; } // Normalize spaces - src = src.replace(/\u00a0/g, ' '); + src = src.replace(SPACES_RE, ' '); // Normalize newlines - src = src.replace(/\r\n/, '\n'); - src = src.replace(/\r\u0085/, '\n'); - src = src.replace(/[\u2424\u2028\u0085]/g, '\n'); + src = src.replace(NEWLINES_RE, '\n'); // Replace tabs with proper number of spaces (1..4) if (src.indexOf('\t') >= 0) { - src = src.replace(/[\n\t]/g, function (match, offset) { + src = src.replace(TABS_SCAN_RE, function (match, offset) { var result; if (src.charCodeAt(offset) === 0x0A) { lineStart = offset + 1;