Skip to content

Instantly share code, notes, and snippets.

@netha145
Last active July 9, 2023 14:50
Show Gist options
  • Save netha145/abb2705cbad0e5fd7b41114aaa28bfd7 to your computer and use it in GitHub Desktop.
Save netha145/abb2705cbad0e5fd7b41114aaa28bfd7 to your computer and use it in GitHub Desktop.
External String Templates

Javascript sadly lacks ability to template on external strings unlike C# and many other languages. I made this script to add this to javascript. If you really want you can convert this into a prototype of string but I would not recommend that due collision risk. If you really want it here is a paste => https://pastecode.io/s/6sspezv0

Documentation

function returns
externalStringLiterals Promise with templateString variable on .then

Example Code

let demoString = "Hey ladies drop it down just wanna to see {1} {2}"

externalStringLiterals(demoString, ['drop it down','why they didnt made this a feature bru']).then( str =>
        console.log(str)
)

Tips

  • Escape data goes to regex in case of user input to prevent broken matches
  • Use await

License

Code is licensed under public domain, documentation is under CC BY SA

let externalStringLiterals=async(a,b)=>new Promise(d=>{let e=a,c=a.match(/\{.}/g);c.forEach((f,a)=>{e=e.replace(f,b[a]),a>=c.length-1&&d(e)})})
let externalStringLiterals = async (string, correspondingStrings) => new Promise((finish) => {
let templateString = string
let templates = string.match(/\{.}/g)
templates.forEach((str,index) => {
templateString = templateString.replace(str,correspondingStrings[index])
index >= templates.length-1 ? finish(templateString) : ''
})
})
@robnewton
Copy link

robnewton commented Dec 6, 2022

Thanks for posting this. I ended up making some improvements to include the $ (so that brackets can be in the string too without tripping it up). The changes also enable both named variables and numeric (position based in string array) as well as a combination of the two. Added finish if there were no replacements found in the string.

I use it like this:

const templateStr = 'Lets get ${0} and ${1} and a name var ${testVar}!';
const values = ['value1', 'value2'];
const newString = await externalStringLiterals(name, {...values, testVar: 'variableName'});
// returns Lets get value1 and value2 and a name var variableName!

Here is the code:

    new Promise(finish => {
      let templateString = string;
      let templates = [...string.matchAll(/\$\{(\w*)}/g)];
      templates.forEach((str, index) => {
        console.log(`Replacing template item ${str[0]} @ ${str[1]} with ${variables[str[1]]}`, str, str[1], variables);
        templateString = templateString.replace(str[0], variables[str[1]]);
        index >= templates.length - 1 ? finish(templateString) : '';
      });
      finish(string);
    })

@BrunoWinck
Copy link

Thx, i'll reuse your solution @robnewton

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment