How an I insert variables at a specific place in a string?(如何在字符串的特定位置插入变量?)
问题描述
获取模板"字符串并将信息插入其中的最佳方法是什么.
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;
正则表达式解释:
{
:匹配{
括号文字([^}]*)
:匹配}
以外的任何内容零次或多次,并将其添加到第一个捕获的组中.}
:匹配}
括号文字g
:全局标志.匹配遵循此模式的所有可能字符串.
{
: Match{
bracket literal([^}]*)
: Match anything other than}
zero or more number of times and add this in the first captured group.}
: Match}
bracket literalg
: 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
.
这篇关于如何在字符串的特定位置插入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在字符串的特定位置插入变量?


基础教程推荐
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01