0

Here's what I'm trying to achieve.

let something = 'first string';
let template = `asdf=${something}asdf`;

some.method(template)
    .then(function() {
       let something = 'new string';
       console.log(template); 
       // does not return 'asdf=new stringasdf' like expected
    });

How would I keep the template, but switch out a variable inside it whenever I want (inside a scoped function)?

1
  • The problem with your current design is that passing a templated string basically evaluates the string to a regular one before the passing happens. This is not entirely unexpected behaviour, considering the passed template to the some.method may or may not contain the ${something} clause. @Robin's suggestion is the correct approach, wrapping the template in a function to provide the behaviour.
    – Andy
    Commented Jun 10, 2016 at 7:32

2 Answers 2

1

The template is basically shorthand for:

let template = "asdf=" + something + "asdf";

So it is evaluated at the place the template itself appears in the code.

I think you'll want to use a function:

let template = function(something) { return `asdf=${something}asdf`; }

Then you can do:

some.method(template(something)).then(function() { let something = 'new string'; console.log(template(something)); });
-1

Check this function I wrote out:

GitHub: https://github.com/tjcafferkey/stringinject/blob/master/src/index.js

NPM: https://www.npmjs.com/package/stringinject

Allows you to do the following:

var str = "This is a {0} string for {1}"
var newStr = stringInject(str, ["test", "stringInject"]);

// This is a test string for stringInject 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.