1 | function valueExtractor(string, pattern, options = {}) {
|
2 |
|
3 | const defaultOptions = {
|
4 | delimiters: ['{', '}'],
|
5 | partial: false,
|
6 | };
|
7 |
|
8 | const option = {...defaultOptions, ...options}
|
9 | const [startDelimiter, endDelimiter] = option.delimiters;
|
10 |
|
11 | const regex = new RegExp(pattern.replace(new RegExp(`${startDelimiter}(\\w+)${endDelimiter}`, 'g'), '(.*)?'), 'i')
|
12 |
|
13 |
|
14 | const values = string.match(regex);
|
15 | const result = {};
|
16 | if (values) {
|
17 | values.shift();
|
18 |
|
19 |
|
20 | let valueIndex = 0;
|
21 | pattern.replace(new RegExp(`${startDelimiter}(\\w+)${endDelimiter}`, 'g'), (match, key) => {
|
22 | let value = values[valueIndex++];
|
23 | result[key] = value !== undefined ? value : null;
|
24 | });
|
25 | }
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | return result;
|
34 | }
|
35 | module.exports = valueExtractor; |
\ | No newline at end of file |