How to: fmt.Sprintf in JavaScript

String interpolation is a common feature of most languages, with which we can insert variables into existing strings, either for output to the user or other systems like via structured log lines.

GO

Go does not support string interpolation like other languages, but you can return formatted strings and store them in variables.

Note that you either need to define the correct type for a value that will be part of your new string or you can use %v if you might have ambiguous inputs, which might yield exciting results and unexpected formatting.

package main

import "fmt"

func main() {
  greetString := fmt.Sprintf("Hello %s!", "Jonathan")
  fmt.Println(greetString)
  // output: Hello Jonathan!
}

JavaScript

Template literals were added to JavaScript with ECMAScript 6, before that we just used the + operator to concatenate strings in the correct order.


const dynamicValue = 'vanilla';
const interpolatedString = `My favourite ice cream flavour is ${dynamicValue}!`
// My favourite ice cream flavour is vanilla!

const oldSchool = 'My favourite ice cream flavour is' + dynamicValue + '!';