forked from EbookFoundation/free-programming-books-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrings.js
More file actions
45 lines (42 loc) · 1.24 KB
/
Strings.js
File metadata and controls
45 lines (42 loc) · 1.24 KB
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
/**
* Strip wrapped parenthesis from a string.
* @param {string} s - the string to process
* @returns {string} the stripped string if parens found, the input string if don't
*/
function stripParens(s) {
// null or undefined
if (s === null || s === void 0) return s;
// is wrapped by ( and )?, then unwrap
if (s.slice(0, 1) === "(" && s.slice(-1) === ")") return s.slice(1, -1);
// leave as it is
return s;
}
/**
* Replaces a data tokens in a template string.
* @param {string} template - the template string
* @param {object} context - the data used to replace the tokens with
* @returns string replace
*/
function templater(template, context = {}) {
// replaceAll using a replacer function
return template.replace(
/{{([^{}]+)}}/g, // {{key}}
(matchedText, key) => context[key] || ""
);
}
/**
* Wraps a string between other that acts as token.
* @param {string} s - the text to wrap
* @param {string} token - the text to wrap with between
* @returns a string in the form `${token}${s}${token}`
*/
function wrap(s, token = "") {
// avoid mix concatenate/sum string/numbers using array join hack
//return `${token}${s}${token}`;
return [token, token].join(s);
}
module.exports = {
stripParens,
templater,
wrap,
};