Search code examples
javascriptregexregex-lookaroundslookbehind

How to extract the strings within brackets using lookbehind and lookahead zero-length assertions?


I want to extract 0 and inner_string from "string[0][inner_string]"

My approach uses lookbehind and looahead zero-length assertions.

This is the regex:

              +--- Look ahead
              |
              v
/(?<=\[)(.*?)(?=\])/g
  ^
  |
  +--- Look behind

var str = "string[0][inner_string]";
console.log(str.match(/(?<=\[)(.*?)(?=\])/g));

However, I'm getting an error.

Is it that possible using lookaround?


Solution

  • Quote by @ctwheels: "Lookbehinds have little support in JavaScript (see the current stage of the TC39 proposal). At the time of writing this only Chrome (starting with version 62) and Moddable (after Jan 17, 2018) support lookbehinds in JavaScript."

    Regex: \[([^\]]+)\]

    str = 'string[0][inner_string]'
    re = /\[([^\]]+)\]/g
    
    while(match = re.exec(str)) {
      console.log(match[1])
    }