如何在字符串的特定位置插入变量? [英] How an I insert variables at a specific place in a string?

查看:23
本文介绍了如何在字符串的特定位置插入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取模板"字符串并将信息插入其中的最佳方法是什么.

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

例如:

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.

推荐答案

可以使用 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 之前的版本,您可以使用正则表达式替换变量.为此,可以创建一个具有搜索替换值的对象,并且 String#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;

正则表达式解释:

  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.

这篇关于如何在字符串的特定位置插入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆