简体   繁体   English

如何在JavaScript中转义单引号或双引号?

[英]How to escape single or double quote in JavaScript?

I am trying to replace quote (') with \\' so as to escape escape quote or double quote in string 我试图用\\'替换引号('),以便转义转义符或字符串中的双引号

<ul id="list">

</ul>
<button id="sethrefbtn" onclick="setlink();">Set Link</button>

function setlink(){    
    var data = {  
        playerID : 102458,
        playername: "Real Madrid's cristiano Ronalado"
    }  
listring= "<li><a href='SearchServlet?q=" + data.playername.replace(/'/g, "\'"); + "&playerid=" + data.playerID + "&page=1#pg0'>"+ data.playername +"</a></li>";      

 $("#list").append(listring);

}

Here is fiddle: fiddle 这是小提琴: 小提琴

The desired output should be: 所需的输出应为:

<a href="SearchServlet?q=Real Madrid's cristiano ronalado&playerid=102458&page=1#pg0">Real Madrid's cristiano Ronalado</a>

Your problem is being caused by it being in an HTML attribute (so you need to convert it to an HTML character reference and not escape it). 您的问题是由它在HTML属性中引起的(因此您需要将其转换为HTML字符引用,而不是对其进行转义)。 You should deal with that by using DOM instead of string mashing to build your HTML. 您应该通过使用DOM而不是字符串混搭来构建HTML来处理。

However, in this particular case, you are putting it in a URL, so you should be escaping it for URLs first. 但是,在这种情况下,您要将其放入URL中,因此应首先将其转义为URL。

You can do that with encodeURIComponent , but since you are building an entire query string and are using jQuery, you can use param instead. 您可以使用encodeURIComponent做到这一点,但是由于要构建整个查询字符串并使用jQuery,因此可以改用param

 function setlink() { var data = { playerid: 102458, q: "Real Madrid's cristiano Ronalado", page: 1 } var url = "SearchServlet?" + $.param(data); var li = $("<li />").append( $("<a />").text(data.q).attr('href', url) ); $("#list").append(li); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="list"> </ul> <button id="sethrefbtn" onclick="setlink();">Set Link</button> 

listring= "<li><a href='SearchServlet?q=" + data.playername.replace(/'/g, "\'") + "&playerid=" + data.playerID + "&page=1#pg0'>"+ data.playername +"</a></li>";

Just replace the above statement in the code . 只需将上面的语句替换为代码即可。 There is a semicolon in the middle of the statement in your code. 您的代码中语句中间有一个分号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM