UNPKG

1.14 kBJavaScriptView Raw
1function 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 // Extract the values from the string
14 const values = string.match(regex);
15 const result = {};
16 if (values) {
17 values.shift();
18
19 // Create an object with keys based on the pattern and values based on the extracted values
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 // else if (partial) {
27 // // Create an object with keys based on the pattern and null values for all keys
28 // pattern.replace(new RegExp(`${startDelimiter}(\\w+)${endDelimiter}`, 'g'), (match, key) => {
29 // result[key] = null;
30 // });
31 // }
32
33 return result;
34}
35module.exports = valueExtractor;
\No newline at end of file