Javascript function parameter character escape - javascript

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..

Related

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:
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.

issue with apostrophes and double quotes in Javascript

I'm having trouble adding in a variable into the following line of JavaScript:
row.insertCell(0).innerHTML = "<div onClick='Myfunction(" + Password + ");'></div>"
how do I add in the password variable I'm getting confused with apostrophes and double quotes
I think it needs to put the value in-between apostrophes but this clashes with what's already there?
Try this example:
var Password ='sample';
document.getElementById("id1").value= '<div onClick="Myfunction(\'' + Password + '\');"></div>';
alert(document.getElementById("id1").value);
This is called Escaping. Use backslash() for the character which you want to escape.
Try this: row.insertCell(0).innerHTML = "<div onClick=Myfunction('" + Password + "');></div>"
you can try escape quotes with backslashes like this
row.insertCell(0).innerHTML = "<div onClick='Myfunction(\"" + Password + "\");'></div>"

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>";

Function not called via javascript in href

I used a code that I found in the web and then changed a little thing:
<script type="text/javascript">
var foodList = [];
function addToFood (addFood) {
alert(addFood);
//foodList.push(addFood);
//for (i = 0; i < foodList.length; i++) {
// var newFood = "<a href='#' onClick='removeRecord(" + i + ");'>X</a> " + foodList[i] + " <br>";
//};
//document.getElementById('foods').innerHTML += newFood;
}
</script>
At this moment I only want to alert the parameter on addToFood. The function should be called:
echo "<a href='javascript:addToFood(". $zeile1['TITLE'] .");' class='band-head'>Add</a>";
this line shows how I add an <a> with the javascript in the href. The php render the right line but the addToFood is never called.
Have a look at the online Demo: http://anthraxx.sytes.net/ maybe it can help you more then me.
The error I get via Google Chrome: Uncaught SyntaxError: Unexpected identifier But just can't figure that unexpected identifier out.
Thanks
You need to wrap the $zeile1['TITLE'] inside a string, as such:
echo "<a href='javascript:addToFood(\"". $zeile1['TITLE'] ."\");' class='band-head'>Add</a>";
You can see that I added escaped quotes \" after the opening parenthesis, and before the ending one, in the JS-call.
Otherwise it will try to pass an variable to the function, instead of a string.
Why escaped? That is because you are echo:ing it with PHP. If I didn't escape the quote, the PHP would interpret it as I was ending the string, which is not what we want. I want to put the quotes in there as inline-code.
Just scope your vaiable between ' ' or " " ,When you don't scope String's ,javascript read it like Var.
You need to escape the $zeile1['TITLE'], thats true and you can do that by using following line -
echo "<a href='javascript:addToFood(\"". $zeile1['TITLE'] ."\");' class='band-head'>Add</a>";
This is working.
try this
echo 'Add';
Replace :
echo "<a href='javascript:addToFood(". $zeile1['TITLE'] .");' class='band-head'>Add</a>";
With:
echo "<a href='javascript:addToFood(\"". $zeile1['TITLE'] ."\");' class='band-head'>Add</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);
​

Categories