geoctrl
geoctrl

Reputation: 685

Regex - capture tagged template literal

I need help building a regex to find all the tagged template literals in a js file

example:

const thing = test`
  background-color: red;
`;

regex result:

test`
  background-color: red;
`

I can accomplish this with:

(test`(?:[^`])*`)

the problem is I can't figure out how to exclude inner template literals.

For example:

const thing = test`
  background-color: ${show ? `red` : `blue`};
`;

expected regex match:

test`
  background-color: ${show ? `red` : `blue`};
`

actual match:

test`
  background-color: ${show ? `

any ideas?

Upvotes: 0

Views: 580

Answers (1)

Alon Valadji
Alon Valadji

Reputation: 628

Regular Expression won't help you here, it is best to parse the JS file with an AST parser like @babel/parser - https://babeljs.io/docs/en/next/babel-parser.html

Upvotes: 4

Related Questions