且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript在字符串中的特定位置插入变量

更新时间:2022-12-28 13:00:31

您可以使用ES2015 模板文字。但是,变量应该在使用之前定义。

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;

对于ES2015之前的版本,您可以使用正则表达式替换变量。为此,可以创建具有搜索替换值的对象,并且 字符串#replace

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说明:


  1. \ {:匹配 {括号文字

  2. ([ ^}] *):匹配}以外的任何内容零次或多次,并将其添加到第一个捕获的组中。

  3. \} :匹配} 括号文字

  4. g :全局标志。匹配此模式后面的所有可能字符串。

  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.

注意: $ 0 是完整的字符串,即 {foo} $ 1 是第一个被捕获的组 foo

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