escaping - How to escape single or double quote in JavaScript? -


i trying replace quote (') \' 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 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 being caused being in html attribute (so need convert html character reference , not escape it). should deal using dom instead of string mashing build html.

however, in particular case, putting in url, should escaping urls first.

you can encodeuricomponent, since building entire query string , using jquery, 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>


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -