Developer Desk
Developer Desk

Reputation: 2344

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>

Upvotes: 0

Views: 900

Answers (2)

Amaranadh Meda
Amaranadh Meda

Reputation: 724

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.

Upvotes: 1

Quentin
Quentin

Reputation: 944443

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>

Upvotes: 3

Related Questions