Skip to content

Instantly share code, notes, and snippets.

@Le0X8
Last active April 22, 2025 14:03
Show Gist options
  • Save Le0X8/cf0a0405f1147dee827e7f8cbf03d8fa to your computer and use it in GitHub Desktop.
Save Le0X8/cf0a0405f1147dee827e7f8cbf03d8fa to your computer and use it in GitHub Desktop.
Replace variables in a string (JS one-liner)
// one-liner version
('hello {name}') // input string
.split('{') // start of variable
.map(s => s.split('}')) // end of variable
.flat()
.map((s, i) => i & 1 ? ({ name: 'world' })[s] ?? `{${s}}` : s) // variable lookup with fallback
.join(''); //> "hello world"
// with variables
const inputString = 'hello {name}';
const varStart = '{';
const varEnd = '}';
const variables = {
name: 'world'
};
const outputString = inputString
.split(varStart)
.map(s => s.split(varEnd))
.flat()
.map((s, i) => i & 1 ? variables[s] ?? `${varStart}${s}${varEnd}` : s)
.join('');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment