How to escape single or double quote in JavaScript? - 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:
Real Madrid's cristiano Ronalado

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.

Related

Href how to pass dynamic data

[![enter image description here][1]][1]In href how to pass path with dynamic data, below I'm giving my code:
var abc = response[i].DocumentName;
var photoName = "<a href='#Url.Content("~/UploadImage/")" + abc +'" target="_blank" >'+response[i].DocumentName+'</a>';
in debugger mode i am getting like this:-
photoName = "jpeg2_10514.jpg"
which is not working for me
Try this:
var photoName = "" + response[i].DocumentName + "";
In Javascript you have to escape doublequotes " with a backslash \ if you want them to appear in the string.
The backslash in + abc + "\" is there to escape the second " to enclose the href in doublequotes.
EDIT
I added the missing doublequote befor the anchor tag according to the tip of karan.

How to display a div inside colorbox - Jquery Plugin

I want to display a div inside Colorbox plugin, but it is not working as there are many double quotes inside the div element and is causing problems so how can I do it.
Here is my code
<script>
$(document).ready(function() {
if(localStorage.getItem('welcomehelloState') != 'shown'){
function openColorBox(){
$.colorbox({transition: "fade", top: "2%", width:"67%", height:"17%", html: "<section class="related">
<p>New Content:-</p>
<a href="/part-2/index>
<img src="img/related/Prdha.png" />
<h3>Art</h3>
</a>
<a href="/part-2/index6">
<img src="img/related/Kavi.png" />
<h3>Games</h3>
</a>
</section>"});
}
setTimeout(openColorBox, 100);
localStorage.setItem('welcomehelloState','shown')
};});
</script>
As you can see there are many double quotes and the brackets are not syncing.
The problem is that when you start a string with a double-quote (") and you place an other quote in the string, JS thinks you ended the string. Thats why the quotes which have to be in the string, have to be escaped: \"
Example: var x = "En then he said: \"Hi there\", with a big smile";
Also, JS does not like linebreaks. you have to escape these too if you need it badly, but the better way is to break the string into multiple strings
Example:
var x = "this is" +
"A multiline" +
"String.";
Your code, escaped well, has to be this:
<script>
$(document).ready(function() {
if(localStorage.getItem('welcomehelloState') != 'shown'){
function openColorBox(){
$.colorbox({transition: "fade", top: "2%", width:"67%", height:"17%", html: "<section class=\"related\">" +
"<p>New Content:-</p>" +
"<a href=\"/part-2/index\">" +
"<img src=\"img/related/Prdha.png\" />" +
"<h3>Art</h3>" +
"</a>" +
"<a href=\"/part-2/index6\">" +
"<img src=\"img/related/Kavi.png\" />" +
"<h3>Games</h3>" +
"</a>" +
"</section>"});
}
setTimeout(openColorBox, 100);
localStorage.setItem('welcomehelloState','shown')
}
});
</script>
If you are using Jquery and making html then make sure there is no enter in lines as jquery won't accept this and it will create an syntax error. use your code in this way..
$.colorbox({transition: "fade", top: "2%", width:"67%", height:"17%", html: '<section class="related"><p>New Content:-</p><img src="img/related/Prdha.png" /><h3>Art</h3><img src="img/related/Kavi.png" /><h3>Games</h3></section>'});
Thank you :)

Passing an array to a function and escaping double quotes in Javascript

I am generating dynamic HTML and want to pass an array to the calling function. The array is also being dynamically generated.
The contents of pinfoarray are somewhat like this "Ice Hockey","Junior Basketball","Ladies Soccer"
var theHost = "<a href='#someDialog' onclick='chnghost(' + pinfoarray + ');' data-toggle='modal' class='button'>Change</a>";
How can make it send the array to the calling function without an error.
How about making it like this:
var anchor = document.createElement('a');
anchor.href = '#someDialog';
anchor.setAttribute('data-toggle','modal');
anchor.className='button';
anchor.onclick = function(){
chnghost(pinfoarray);
}
You need to properly terminate the string and encode the parameter. You also need to guard against reserved characters in your data (escapeHtml).
var theHost = "<a href='#someDialog' onclick='chnghost(" + escapeHtml(JSON.stringify(pinfoarray)) + ");' data-toggle='modal' class='button'>Change</a>";
If you're using jQuery, you can implement escapeHtml like so:
function escapeHtml(text) {
return $("<div/>").text(text).html();
}
You need to close the string double quote to put a javascript variable:
var theHost = "<a href='#someDialog' onclick='chnghost('" + pinfoarray + "');' data-toggle='modal' class='button'>Change</a>";

JavaScript regex replace inner quotes

I'm trying to fix an inline javascript snippet with reg ex to be rewritten on an input field.
I have single quotes that wrap the inner double quotes and I want to convert the inner quotes to be single instead of double but I only want to convert them when the code appears as nested quotes.
Right now I'm doing the conversion for all instances of the quote which works but I might run into another problem. I'll attach my code below.
JavaScript
$(document).ready(function() {
$('.submit').bind('click', function(e) {
var yourstring = $("textarea").val();
yourstring = yourstring.replace(/'/g, "''");
yourstring = yourstring.replace(/&quote;/g, "\"");
yourstring = yourstring.replace(/&lquote;/g, "\"");
yourstring = yourstring.replace(/&rquote;/g, "\"");
yourstring = yourstring.replace(/&#34/g, "\"");
yourstring = yourstring.replace(/“/g, "\"");
yourstring = yourstring.replace(/”/g, "\"");
yourstring = yourstring.replace(/"/g, "\"");
alert(yourstring)
});
});​
HTML
<textarea style="width:400px;height:300px;">
function('');
<a onclick="$(".text").append('test');">Click Me</a>
<br/>
&lquote;test quotes&rquote;
" generic quotes "
</textarea>
<input type="submit" class="submit">
To be more specific I'm trying to get
<a onclick="$(".text").append('test');">Click Me</a>
To look like
<a onclick="$('.text').append('test');">Click Me</a>
The example provided does not seem to have anything to do with the database but a problem with the JavaScript code within the onclick attribute. That code actually doesn't have a valid syntax, but my guess is that you are trying to build some sort of editor for HTML code.
If you decide not to follow the recommendations in the comments above (which I agree with), to answer your question, here's an option for removing double quotes for text already surrounded by them:
var s = "<a onclick=\"$(\".text\").append('test');\">Click Me</a>";
var re = /"(.*)"/g;
var r = s.replace(re, function($0, $1) { return '"' + $1.replace(/"/g, "''") + '"'; });
console.log(r);
​

Javascript function parameter character escape

I need to pass a variable to a JavaScript function, but I have a little trouble. In the .cs file, I have written:
string id = "some'id";
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction('"+id+"')\">"));
As you can see there is an ' (single quote) in the id. Is there any way to work around this issue?
Escape ' with a \ (backslash). For example,
console.log('string with \'');
Escape your string for such kind of characters"/","\","'"
example
string id = "some/'id";
You should escape your string , which would lead to :
id = "some\'id";
<script type="text/javascript">
function myFunction(someid) {
someid = someid.replace('#', '\'');
alert(someid);
}
</script>
in Your code
string id = "some'id".Replace("'","#");
this.Controls.Add(new LiteralControl("<input type=\"button\" value=\"Test\" onclick=\"myFunction('" + id + "');\">"));
Hope this will Helps you..

Categories