Shivam Sinha
Shivam Sinha

Reputation: 11

Extract string between braces but exclude some

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

Answers (3)

Vincent
Vincent

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

sibasishm
sibasishm

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

Rajesh
Rajesh

Reputation: 24915

You can try to use regex to define the pattern.

Logic

  • Start looking for pattern if { or {{{ is either start of string or is preceded by space.
  • Capture any string until } 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))

References:

Upvotes: 1

Related Questions