Javascript insert variables at a specific place in

2019-03-02 13:29发布

What is the best method to take a 'template' string and insert information into it.

For example:

var templateString = "Hello {name1}, my name is {name2}";
var name1 = "Phil";
var name2 = "Amy";

Would there be an easy name to insert the values where the variable name surrounded by braces is? I need this to work not only for this example (so doing it by a fixed index is not an option) but for any given template string and any given number of variables.

4条回答
爷、活的狠高调
2楼-- · 2019-03-02 14:06

You can use ES2015 template literals. But, the variables should be defined before using them.

var name1 = "Phil";
var name2 = "Amy";
var templateString = `Hello ${name1}, my name is ${name2}`;

console.log(templateString);
document.body.innerHTML = templateString;

For pre-ES2015, you can use regex to replace the variables. For this, an object having the search-replace values can be created and String#replace with function as parameter can be used.

The regex \{([^}]*)\} can be used to match the strings which are surrounded by the curly brackets.

// Create an object of the key-value of search-replace
var obj = {
    name1: "Phil",
    name2: "Amy"
};

var templateString = "Hello {name1}, my name is {name2}";

// Use replace with callback function
var result = templateString.replace(/\{([^}]*)\}/g, function($0, $1) {
    return obj[$1] || $0; // If replacement found in object use that, else keep the string as it is
});

console.log(result);
document.body.innerHTML = result;

RegEx Explanation:

  1. \{: Match { bracket literal
  2. ([^}]*): Match anything other than } zero or more number of times and add this in the first captured group.
  3. \}: Match } bracket literal
  4. g: Global flag. Match all possible strings that follows this pattern.

Note: $0 is the complete string i.e. {foo} and $1 is the first captured group foo.

查看更多
Summer. ? 凉城
3楼-- · 2019-03-02 14:13

ES6 has string interpolation, you can do it like this

var name1 = "Phil";
var name2 = "Amy";
var templateString = `Hello ${name1}, my name is ${name2}`;

document.write(templateString);

查看更多
SAY GOODBYE
4楼-- · 2019-03-02 14:28

you can use the javascript function replace: http://www.w3schools.com/jsref/jsref_replace.asp

so your code would be:

var templateString = "Hello {name1}, my name is {name2}";
var name1 = "Phil";
var name2 = "Amy";

templateString = templateString.replace('{name1}', name1);
templateString = templateString.replace('{name2}', name2);

please let me know if this doesn't work.

查看更多
Melony?
5楼-- · 2019-03-02 14:28

In ES5, you could use String.replace:

var templateString = "Hello {name1}, my name is {name2}";
var name1 = "Phil";
var name2 = "Amy";

templateString.replace(/\{([^}]*)\}/g, function (m, v) { return eval(v) || m; })

Note that the use of eval is not recommended. If you set the names in an object, you could do this:

var templateString = "Hello {name1}, my name is {name2}";
var names = {};
names.name1 = "Phil";
names.name2 = "Amy";

templateString.replace(/\{([^}]*)\}/g, function (m, v) { return names[v] || m; })
查看更多
登录 后发表回答