Search code examples
javascriptnode.jsregexnunjucks

Regex: Grab text inside my tag


I'm working on NodeJS read text inside files, But I don't know much about regex for grabbing string, So i'm asking for help.

Example text:

text text {{ 'translate me' | lang }} text {{ 'A' | replace('A', 'B') }} {{"another text"|lang}}

I want to grab text inside Only {{ 'SOMETHING' | lang }}

Output

['translate me', 'another text']

So, how to use Regex for grab, thanks.

Oh, Also it should support some spacing case like

  • {{ 'translate me' | lang }}
  • {{'translate me'|lang}}
  • {{ 'translate me' |lang}}
  • {{'translate me' | lang }}

Also Support " and ' (single and double quote)

  • {{ "translate me" | lang }}

Solution

  • Two opening curlies, followed by zero or more spaces, followed by the quoted string, followed by zero or more spaces, followed by |, lang and two closing curlies, using (new) lookbehind:

    const text = "text text {{ 'translate me' | lang }} text {{ 'A' | replace('A', 'B') }} {{ 'another text' | lang }}";
    console.log(text.match(
      /(?<=\{\{ *')[^']+(?=' *\| *lang *}})/g
    ));
    
    // or, without lookbehind:
    
    const re = /\{\{ *'([^']+)(?=' *\| *lang *}})/g;
    let match;
    const matches = [];
    while ((match = re.exec(text)) !== null) {
      matches.push(match[1]);
    }
    console.log(matches);