-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (53 loc) · 1.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict';
var defaults = require('lodash.defaults');
var defaultOptions = {
startPrefix: '/*',
startSuffix: '*/',
endPrefix: '/*/',
endSuffix: '*/',
space: true
};
function escapeRegexp(exp) {
return exp.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
function startTag(tagName, options) {
var startPrefix = options.startPrefix;
var startSuffix = options.startSuffix;
return escapeRegexp(startPrefix + tagName + startSuffix);
}
function endTag(tagName, options) {
var endPrefix = options.endPrefix;
var endSuffix = options.endSuffix;
return escapeRegexp(endPrefix + tagName + endSuffix);
}
function regexp(tagName, options) {
var space = '';
if (options.space) {
space = escapeRegexp(' ');
}
return new RegExp(
startTag(tagName, options) + '[\\s\\S]*?' + endTag(tagName, options), 'g');
}
function enclose(tag, content, options) {
var space = '';
if (options.space) {
space = escapeRegexp(' ');
}
var startPrefix = options.startPrefix;
var startSuffix = options.startSuffix;
var endPrefix = options.endPrefix;
var endSuffix = options.endSuffix;
return startPrefix + tag + startSuffix + space + content + space + endPrefix + tag + endSuffix;
}
function TaggedReplace(content, values, options) {
var replaced = content;
options = defaults({}, options, defaultOptions);
if (values && typeof values === 'object') {
var keys = Object.keys(values);
replaced = keys.reduce(function(accum, tag) {
return accum.replace(regexp(tag, options), enclose(tag, values[tag], options));
}, replaced);
}
return replaced;
}
module.exports = TaggedReplace;