简体   繁体   中英

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). You should deal with that by using DOM instead of string mashing to build your HTML.

However, in this particular case, you are putting it in a URL, so you should be escaping it for URLs first.

You can do that with encodeURIComponent , but since you are building an entire query string and are using jQuery, you can use param instead.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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