Skip to content

Instantly share code, notes, and snippets.

@kapraran
Last active March 2, 2019 17:57
Show Gist options
  • Save kapraran/e2398d2626d36610413e to your computer and use it in GitHub Desktop.
Save kapraran/e2398d2626d36610413e to your computer and use it in GitHub Desktop.
an alternative string format function in javascript
function printf() {
const args = Array.from(arguments)
let str = args.shift()
return args.reduce((str, val, i) => {
let reg = new RegExp(`\\{${i}\\}`, 'g')
return str.replace(reg, val)
}, str)
}
// usage
printf("My name is {0} and i am from {1}", "Nick", "Greece");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment