Go (RE2)

JavaScript Template Literal Placeholder in GO

Match `${expression}` placeholders inside JavaScript template literals.

Try it in the GO tester →

Pattern

regexGO
\$\{([^{}]+)\}   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`\$\{([^{}]+)\}`)
	input := "`Hello ${name}, you have ${count} items`"
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

How the pattern works

\$ matches the dollar sign. \{ matches the opening brace. ([^{}]+) captures one or more non-brace characters as the inner expression. \} matches the closing brace. The pattern won't handle nested braces (e.g. `${ {a:1}.a }`); for that you need a real parser, but this regex covers the common case.

Examples

Input

`Hello ${name}, you have ${count} items`

Matches

  • ${name}
  • ${count}

Input

const url = `https://api.com/${endpoint}?key=${apiKey}`

Matches

  • ${endpoint}
  • ${apiKey}

Input

no placeholders

No match

Same pattern, other engines

← Back to JavaScript Template Literal Placeholder overview (all engines)