Reputation: 11
Given Input:
{abcd} {{abcd}} {{{abcd}}}
How can I extract texts which are surrounded by either single braces or triple braces? I don't text if double braces surround it.
Output:
{abcd} {abcd}
The second {abcd} in the output is extraced from {{{abcd}}}
Do you have any ideas?
Upvotes: 0
Views: 52
Reputation: 4753
If you're not obsessed with performance, doing it in 2 .replaces()
makes it very easy :
"{abcd} {{abcd}} {{{abcd}}}".replace(/(\s|^){{\w+}}/g,'').replace(/{{({\w+})}}/g, '$1')
1st step replace(/(\s|^){{\w+}}/g,'')
removes {{ }} elements
2nd step replace(/{{({\w+})}}/g, '$1')
transforms {{{ }}} to { }
Upvotes: 1
Reputation: 442
In case you want a non-regEx solution, please check this out. I have tried to make it as simple and extensive as possible using common JS methods like: Array.fill() and String.split()
function textExtractor(input, startChar, endChar, count, ignoreFlag) {
let startExpression = new Array(count).fill(startChar).join("");
let endExpression = new Array(count).fill(endChar).join("");
if (ignoreFlag) return input;
else return input.split(startExpression)[1].split(endExpression)[0];
}
console.log(textExtractor("{abc}", "{", "}", 1, false));
console.log(textExtractor("{{abc}}}", "{", "}", 2, true));
console.log(textExtractor("{{{abc}}}", "{", "}", 3, false));
Upvotes: 1
Reputation: 24915
You can try to use regex to define the pattern.
{
or {{{
is either start of string or is preceded by space.}
or }}}
You will have to use non-capturing(?:
) groups to define the start and end.
var str = '{abcd} {{efgh}} {{{ijkl}}}';
var regex = /(?:^| )(?:\{|\{{3})(\w+)(?:\}|\}{3})/g
console.log(str.match(regex))
Upvotes: 1