Commit f8ede7d096c4725b13f8dab267b99400a2d59570
1 parent
a4e4646bf4
Exists in
master
extract-from-msg
Showing 1 changed file with 32 additions and 0 deletions Side-by-side Diff
extract-from-msg.js
... | ... | @@ -0,0 +1,32 @@ |
1 | +"use strict"; | |
2 | + | |
3 | +function extractFromMessage(msg, default_pattern, default_match_idx, custom_rule) { | |
4 | + if (!msg || typeof msg !== 'string') { | |
5 | + return; | |
6 | + } | |
7 | + | |
8 | + let pattern; | |
9 | + let match_idx; | |
10 | + | |
11 | + if (custom_rule && custom_rule.pattern) { | |
12 | + pattern = custom_rule.pattern; | |
13 | + match_idx = custom_rule.match_idx; | |
14 | + } | |
15 | + else { | |
16 | + pattern = default_pattern; | |
17 | + match_idx = default_match_idx; | |
18 | + } | |
19 | + | |
20 | + const re = new RegExp(pattern); | |
21 | + const matches = msg.match(re); | |
22 | + | |
23 | + if (!matches) return; | |
24 | + | |
25 | + if (match_idx < matches.length) { | |
26 | + return matches[match_idx] || null; | |
27 | + } else { | |
28 | + return; | |
29 | + } | |
30 | +} | |
31 | + | |
32 | +module.exports = extractFromMessage; |