Home > other >  Regex in Javascript to find incomplete items that begin and end with brackets
Regex in Javascript to find incomplete items that begin and end with brackets

Time:04-07

I'm trying to use regex to find any incomplete things that begin with {{.

I've tried to check for any places in the string that begin with {{ and have a-Z after it but haven't been ended (}}). What I'm trying always returns null.

string = 'Hello {{name}}, you are {{a';
console.log(string.match(/^({{)?[a-z]:[A-Z]$/g));

My expected output would be {{a in this case because {{name}} is complete. Any help really appreciated.

The only things it will have between it is . ie: {{name.forename}} {{name.lastname}}

CodePudding user response:

You can use the "best regex trick ever", in this case, match all word char chunks between double curly braces or match and capture any {{ followed with zero or more word chars:

Array.from(text.matchAll(/{{\w (?:\.\w )*}}|({{(?:\w (?:\.\w )*)?)/g), x => x[1]).filter(Boolean)

Here,

  • {{\w (?:\.\w )*}} - {{, one or more word chars, zero or more sequences of a . and one or more word chars, }}
  • | - or
  • ({{(?:\w (?:\.\w )*)?) - Group 1: {{ and an optional occurrence of one or more word chars and zero or more sequences of a . and one or more word chars.
  • Related