Search code examples
javascriptstringbackticks

How to split ``(Backtick string) on each instance of ${variable}


So my question is how i can split the a string with backtick on each instance of variable.

I tried with \${.*?} but this will not work because ${variable} will be replaced by variable values first and than the split function will be executed.

Any idea how to do it ?

let a = 2
let b = 4
let x = `Superman${a}hello${b}one more`.split(/\${.*?}/g)

console.log(x)

On side not: I don't want a solution with wrapping it to " or '.

console.log('`Superman${a}hello${b}one more`'.split(/\${.*?}/g))


Solution

  • To clarify my comment to the original question here is an example of what the default Template Literal Function does:

    function defaultTemplateLiteralFn(strs, ...args) {
      return strs.map((str, idx) => str+(args[idx]||'')).join('');
    }
    
    const test = "special test";
    const a = 10;
    const b = 432;
    console.log(`This is a ${test}. "${a}+${b}=${a+b}"`)
    console.log(defaultTemplateLiteralFn`This is a ${test}. "${a}+${b}=${a+b}"`)

    When you use a tagged template (IE: You don't provide a function to handle the template literal) The the language provides a default function that does something similar to what I do in my function defaultTemplateLiteralFn above. It returns the combined parts of the string with the values.

    The example function takes each part of the string and puts the appropriate value after the string. If there is no value then it uses a blank string.