Last active
April 22, 2025 14:03
-
-
Save Le0X8/cf0a0405f1147dee827e7f8cbf03d8fa to your computer and use it in GitHub Desktop.
Replace variables in a string (JS one-liner)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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