Search code examples
javascriptstringecmascript-6template-strings

Javascript template string


I need to create some substrings using the template string. I try to use this code but I have some problem about the auto filling of the template.

        Object.keys(optionsParams).forEach(function (key) {
            let template = '&${key}=${value}';
            let value = optionsParams[key];
            url += template;
        });

key and value variables are not found. What's the problem?


Solution

  • To use template strings you need to use backticks ` instead of single or double quotes. Try the following code instead

    Object.keys(optionsParams).forEach(function (key) {
        let value = optionsParams[key];
        let template = `&${key}=${value}`
        url += template;
    });