1

I have two sample strings of code like so:

"const x = anything;"
"const {a, b, c, d} = anything;"

I want to match x, as well as a, b, c, and d (none of which are literal, they can be any valid JavaScript variable character(s), but are delimited by commas) if they are preceded by the keyword const. The latter is the destructuring syntax.

Context: this is to extend syntax highlighting of code tokens in PrismJS.

What I've tried so far:

  Prism.languages.insertBefore(lang, 'operator', {
    constant: {
      pattern: /(const\s?{?)[\s_$a-zA-Z\xA0-\uFFFF,]*(?!:)/,
      lookbehind: true,
    },
  });

The comma is inside the [], and I am not sure of how to "continue" matching each variable inside the braces without including the comma character.

frosty
  • 2,779
  • 6
  • 34
  • 63

1 Answers1

0

Try this pattern:

(?:const\s+{?\s*)[_$\w]+(?:[,}\s])

I'll try and improve it by replacing \w to match identifiers using non-alphanumeric characters. Possibly:

(?:const\s+{?\s*)[_$\p{L}]+(?:[,}\s])
Inigo
  • 12,186
  • 5
  • 41
  • 70