如何在JavaScript中的URL路径中呈现变量?

时间:2014-08-28 21:06:52

标签: javascript

我有以下一行:

var myCustomVariable = '3434';
urlpath = '/people/myCustomVariable/folders/byid/'

我想在urlpath中呈现myCustomVariable的值,但是对JS来说是新手,我无法解决这个问题。我尝试过以下但是没有工作:

"+myCustomVariable+"!"

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您使用+运算符:

var myCustomVariable = '3434';
urlpath = '/people/' + myCustomVariable + '/folders/byid/'

这称为“串联”或(因为我们正在处理字符串)“字符串连接。”

您的“我尝试过以下操作...”使用双引号和!。我不确定!来自哪里,但是在JavaScript中,如果打开带有单引号的字符串,则必须以单引号结尾;如果你用双引号打开它,你必须用双引号结束它。

答案 1 :(得分:1)

只需像这样串联字符串:

var myCustomVariable = '3434';
urlpath = '/people/' + myCustomVariable  + '/folders/byid/'

执行此操作时:

"+myCustomVariable+"

表示字符串,而不是变量。你的变量是

myCustomVariable

没有" aroud it

见:

var myCustomVariable = '3434';

//This
urlpath = '/people/' + myCustomVariable + '/folders/byid/'
//Same than
urlpath = '/people/' + '3434' + '/folders/byid/'
//Same than
urlpath = '/people/3434/folders/byid/'

但是

var myCustomVariable = '3434';

//This
urlpath = '/people/' + '+myCustomVariable+' + '/folders/byid/'
//Same than
urlpath = '/people/+myCustomVariable+/folders/byid/'