使用Javascript中的变量格式化字符串模板 [英] Format string template with variables in Javascript
问题描述
我想使用静态定义的模板进行URL构建。
I want to use a statically defined template for URL building.
我正在尝试使用ES6字符串插值功能
I'm trying to use ES6 string interpolation feature for this
var template = "http://example.com/?name=${name}&age=${age}";
var name = "John";
var age = "30";
var url = `${template}`;
预期结果: http://example.com/?name=John&age=23
实际结果: http://example.com/?name= $ {name}& age = $ {age}
Actual result: http://example.com/?name=${name}&age=${age}
如果用字符串插值无法做到这一点,那么有比 String.prototype.replace
更好的方法吗? / p>
In case this can't be done with string interpolation is there any better method than String.prototype.replace
like
var url = template.replace(/\${name}/,"John").replace(/\${age}/, 23);
推荐答案
变量在评估时被替换文字,所以你不能创建一个可以在以后用变量替换的通用模板:
The variables are substituted at the moment of evaluation of the literal, so you can't create a universal template that can be substituted with variables later:
var template = `http://example.com/?name=${name}&age=${age}`;
var name = "John";
var age = "30";
console.log( template ); // "http://example.com/?name=undefined&age=undefined"
编辑:重复使用控制台会话并具有以前实验中定义的变量的人: https://jsfiddle.net/nwvcrryt /
fiddle for those who reuse a console session and have the variables defined from previous experiments: https://jsfiddle.net/nwvcrryt/
您也无法转换字符串文字我的名字是$ {name}
到你想要做的模板。
You also can not convert a string literal "My name is ${name}"
to a template like what you're trying to do.
但是,您可以使用一个取名字和年龄的函数并返回所需的网址:
You can, however, use a function that takes the name and age and returns the desired url:
const formatUrl = (name, age) => `http://example.com/?name=${name}&age=${age}`;
let name = "John";
let age = "30";
let url = formatUrl( name, age ); // "http://example.com/?name=John&age=30"
这篇关于使用Javascript中的变量格式化字符串模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!