Skip to content

Instantly share code, notes, and snippets.

@aslafy-z
Last active September 26, 2024 08:34
Show Gist options
  • Select an option

  • Save aslafy-z/696b3200ccb3ee1c9e3f492d6ac602df to your computer and use it in GitHub Desktop.

Select an option

Save aslafy-z/696b3200ccb3ee1c9e3f492d6ac602df to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strings"
"github.com/distribution/reference"
)
// Converts Golang regex counterparts to JavaScript equivalents
func useJSCounterparts(input string) string {
output := input
output = strings.ReplaceAll(output, `[:xdigit:]`, `0-9a-fA-F`)
output = strings.ReplaceAll(output, `\w`, `A-Za-z0-9`)
return output
}
// Escapes forward slashes for JavaScript regex literals
func escapeSlashes(input string) string {
return strings.ReplaceAll(input, `/`, `\/`)
}
// Escapes backslashes for JavaScript string representation
func escapeBackslashes(input string) string {
return strings.ReplaceAll(input, `\`, `\\`)
}
func main() {
golangRegex := reference.ReferenceRegexp.String()
jsRegex := useJSCounterparts(golangRegex)
escapedJSRegex := escapeSlashes(jsRegex)
escapedJSStringRegex := escapeBackslashes(jsRegex)
fmt.Printf("Golang expression: %s\n", golangRegex)
fmt.Printf("ECMAScript expression: /%s/\n", escapedJSRegex)
fmt.Printf("ECMAScript string expression: %s\n", escapedJSStringRegex)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment