如何使用转义序列将字符串放入href(<a href="">Demo</a>)?

时间:2013-11-25 13:28:05

标签: java escaping

我有以下代码片段,我正在尝试将字符串demoString添加到href。

String demoString = "/helio/demo";
String demoStrUrl = "<a href=demoString ><h3 class="+"demoDetails" +">Details</h3></a>"

3 个答案:

答案 0 :(得分:1)

简单地:

String demoString = "/helio/demo";
String demoStrUrl = "<a href=\"" + demoString + "\"><h3 class=\"demoDetails\">Details</h3></a>";

请注意,如果您要在字符串中添加"符号,则必须使用\

进行转义

答案 1 :(得分:0)

您必须仅使用+将String变量附加为对象。否则它将再次被处理为固定的String而不是您定义的变量。

String demoString = "/helio/demo";
String demoStrUrl = "<a href=\""+demoString+"\" ><h3 class=\"demoDetails\">Details</h3></a>";

答案 2 :(得分:0)

首先逃脱demoString的引用:

String demoString = "\"/helio/demo\"";

然后使用demoStrUrl运算符将其添加到+

String demoStrUrl = "<a href="+demoString+" ><h3 class.....

为了便于转义HTML,您可以查看apache commons StringEscapeUtils类。