You can use a higher order function to return a 'compiled' version of your extractor, that way it's faster.
With regexes, and compiling the regex once in a closure, Javascript's match will return all matches.
This leaves us with only having to remove what we used as our markers (ie: {{
) and we can use string length for this with slice.
function extract([beg, end]) {
const matcher = new RegExp(`${beg}(.*?)${end}`,'gm');
const normalise = (str) => str.slice(beg.length,end.length*-1);
return function(str) {
return str.match(matcher).map(normalise);
}
}
Compile once and use multiple times...
const stringExtractor = extract(['{','}']);
const stuffIneed = stringExtractor('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]
Or single-time use...
const stuffIneed = extract(['{','}'])('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]
Also look at Javascript's replace
function but using a function for the replacement argument (You would do that if for example you were doing a mini template engine (string interpolation) ... lodash.get could also be helpful then to get the values you want to replace with ? ...
My answer is too long but it might help someone!