如何显示<a> tag from JavaScript in HTML by escaping characters

时间:2018-01-02 14:11:27

标签: javascript html escaping

I have a variable in my JavaScript, where I need to pass an anchor tag and a URL to route. But I am getting errors in my JS file and it looks like I need to escape my HTML tags, but it didn't work.

Can some one help?

var link = "<a href="http://localhost:3002/#/login?customerid=" >Continue</a>;

I tried below but it didn't work:

&lt;a href="http://localhost:3002/#/login?customerid=" &gt;Continue&lt;/a&gt;

2 个答案:

答案 0 :(得分:3)

var link = '<a href="http://localhost:3002/#/login?customerid=" >Continue</a>';

错误是因为如果你打开一个字符串,“你必须用它来结束”,但你的href里面的url引用了“”,所以它显然无法使你的字符串变量。我刚刚引用了你的字符串'并且为了href。

答案 1 :(得分:0)

您需要将该行重写为

var link = "<a href=\"http://localhost:3002/#/login?customerid=\" >Continue</a>";

原因是因为Javascript认为字符串在第一个"结束。为了防止这种情况,向后斜杠特别描述了它作为字符串

的一部分

但是,你首先使用它是什么?不建议在字符串中存储HTML。