如何在字符串中使用变量 [英] How to use a variable in a string
问题描述
我正在尝试在字符串中实现变量.我已经搜索过此内容,并尝试将其他内容扔给它,但似乎没有任何效果.
I am trying to implement a variable in a string. I have searched for this and tried throwing different things at it but nothing seems to work..
我有一个看起来像这样的变量:
I have a variable that looks like this:
http:localhost:8080/Editor/?name=Default
我没有问题,可以使用以下方法获取价值:
I have no issue getting the value using:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) { return pair[1]; }
}
return (false);
}
var name = getQueryVariable("name")
现在,我有一个字符串可以加载如下所示的页面:
Now I have a string that loads a page that looks like this:
HMI.Builder.init('Files/HMIBuilder/', function () {
//run code after page/iframe is loaded
});
我要做的是将变量添加到字符串Files/HMIBuilder/{name} 这是行不通的.它最终需要看起来像这样
What I want to do is add the variable to the string Files/HMIBuilder/{name} This does not work. It needs to end up looking like this
Files/HMIBuilder/Default
或者传递任何变量.
推荐答案
您必须使用javascript +
符号将字符串与变量连接起来,如下所示:
You'll have to concatenate your string with the variable using the javascript +
symbol, like below:
HMI.Builder.init('Files/HMIBuilder/' + getQueryVariable("name"), function () {
//run code after page/iframe is loaded
});
或使用方便的replace
来提高可读性:
Or use the handy replace
for more readability:
HMI.Builder.init('Files/HMIBuilder/{name}'.replace('{name}', getQueryVariable("name")), function () {
//run code after page/iframe is loaded
});
当然,您可以通过两个步骤来实现此目的,以提高可读性:
Of course, you could do it with two steps for even more readability:
var route = 'Files/HMIBuilder/{name}'.replace('{name}', getQueryVariable("name"));
HMI.Builder.init(route, function () {
//run code after page/iframe is loaded
});
最后,在最近的浏览器(以及一些向后兼容的编译器)上,您可以使用ES6`"语法:
Finally, on recent browsers (and with some transpilers for backward compatibility), you could use the ES6 "`" syntax:
var route = `Files/HMIBuilder/${getQueryVariable("name")}`;
HMI.Builder.init(route, function () {
//run code after page/iframe is loaded
});
这篇关于如何在字符串中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!