Single Quote in Javascript Param - javascript

I have a function that, when clicked, fills in a field of the parent window. In this case, it's a name (text) field.
The problem I'm having is if the field has a single quote in it (ex. Bill's Chili) the function fails because it reads the single quote as the end of the parameter.
Here is the call:
href="javascript:selectItem('recipe','recipe_name','<recipe_description')"
Again, if the name is Bill's Chili, it causes a syntax error.
Is there a way to automatically convert that single quote to the HTML equivalent so it will read properly?
Thanks

For the single quotes in the field use \' More info on escape characters here.
href="javascript:selectItem('Bill\'s Chilli','recipe_name','<recipe_description')"

The answer I found was completely different than I thought. The page itself is written is ASP (Sorry I forgot to mention that, I didn't think it mattered since the function was javascript and it was called in HTML).
Therefore, I just used this:
<%fixed_name = Replace(recipe_name,"'","") %>
And then used fixed_name instead of recipe_name in the function call.
Thanks for all your help, it set me in the right direction!

try this
href='javascript:selectItem("recipe","recipe_name","<recipe_description")'

You may try to use escaped 'double' quote like that:
href="javascript:selectItem(\"recipe\",\"recipe_name\",\"recipe_description\")"
Please let me know whether it works.

You could use str.replace
Just remplace " by " et ' by ' . :)
But actually, I'm assuming you're getting all of that stuff from a php script (from some sort of storage), in which case you could escape the quotes directly with php, that would be way more safer.

Related

How to code a formula that will call a variable string that may contain quotation marks?

I'm sorry, I know the issue was addressed before, but I can't make any answer fit my problem...
I am writing a short script on google script, where I want to use the searchFile method on a folder, to look for a file whose name is stored in the string variable Name:
var theFileImLookingFor = theSourceFolder.searchFiles("title = '"+Name+"'").next();
This code works fine as long as the variable Name doesn't include quotation marks. Then, I'm stuck...
Please help me adapt my code :)
A simple but fragile solution could be to use backticks (`), usually found on the upper left of the keyboard on the same key as the tilde (~). These are sort of like quotation marks in javascript, but can also be used in ways that quotation marks can't.
Expect this solution to fail whenever the variable's value contains backticks.
Did you try to escape possible quotes ?
You probably could write a little function that take your variable "name" then escape possible quotes in it before returning it to searchFile. Or maybe with a simple "replace("'", "\'")"...

How to parse \n in string while passing the value to javascript

In my code, i need to pass the value present in instance variable to javascript, and then use that value to set onto textarea.
$('textarea.myclass').val('<%= #text_value %>');
But if the variable #text_value contains \n (this is\n demo) then, its leads to javascript error and the page shows exactly as this, separated by space in between,
$('textarea.myclass').val('this is
// error message over here
demo');
Any way i can handle this ?
I also faced such situation, and i just escaped the \ to \\, so finally \n to \\n, \r to \\r
$('textarea.myclass').val('<%= #text_value.gsub("\r","\\r").gsub("\n","\\n") %>');
Hope this corrects you error too.
The best answer I can come up with is to go for a variable. Without testing, this may be answer you are looking for:
var newline = "\n";
$('textarea.myclass').val('this is '+newline+' demo');
As SilverBlade suggested, maybe a double backslash would do the trick.

how do i replace \ character?

i got the following code
replaceforever: function(string,find,replace){
while(_.contains(string,find)){
string.replace(find,replace);
}
return string;}
and i am sending to it something like './routes\admin\articles.js','\\','/'
but it always seem to enter the while loop once and change it all with one '/' as result :|
instead of being a nice ./routes/admin/articles.js
can anyone explain to me please what am i doing wrong?
The problem is with your testing, not with the code (assuming you are using underscore.js;
using regular expressions would be more sensible).
You need to escape your backslashes in the input string:
replaceforever('./routes\\admin\\articles.js','\\','/');
'./routes\admin\articles.js', on the other hand, evaluates to './routesadminarticles.js'.
If I get it right, this will do a global replacement:
stringVariable.replace(/\\/g, '/');
I think the problem is actually that your while-loop isn't being entered at all, rather than that it's being entered once. Note that your input actually already has a /, and I think that's what you're seeing.
This line:
string.replace(find,replace);
creates a new string with the specified replacement . . . and then throws it away. So if your while-loop were being entered even once, it would actually be an infinite loop, because the loop body doesn't actually do anything. Instead, you need to store the result in the variable string:
string = string.replace(find,replace);
But I'm not sure this method is really a good idea anyway. JavaScript already offers "replace-all" functionality, using regexes:
result = input.replace(/\\/g, '/');
First: string.replace() will replace ALL the matches, so there is no need of iteration :)
Second: string.replace() will return a NEW string, it wont change the object used.
So you need something like:
replaceforever: function (string,find,replace) {
return string.replace(find,replace);
}

how to escape JavaScript code in HTML

I have some addHtml JavaScript function in my JS code. I wonder how to escape HTML/JS code properly. Basically, what I am trying right now is:
addHtml("<a onclick=\"alert(\\\"Hello from JS\\\")\">click me</a>")
However, that doesn't work. It adds the a element but it doesn't do anything when I click it.
I don't want to replace all " by ' as a workaround. (If I do, it works.)
I wonder how to escape HTML/JS code properly.
To insert string content into an HTML event handler attribute:
(1) Encode it as a JavaScript string literal:
alert("Hello \"world\"");
(2) Encode the complete JavaScript statement as HTML:
<a onclick="alert("Hello \"world\""">foo</a>
And since you seem to be including that HTML inside a JavaScript string literal again, you have to JS-encode it again:
html= "<a onclick=\"alert("Hello \\"world\\""\">foo<\/a>";
Notice the double-backslashes and also the <\/, which is necessary to avoid a </ sequence in a <script> block, which would otherwise be invalid and might break.
You can make this less bad for yourself by mixing single and double quotes to cut down on the amount of double-escaping going on, but you can't solve it for the general case; there are many other characters that will cause problems.
All this escaping horror is another good reason to avoid inline event handler attributes. Slinging strings full of HTML around sucks. Use DOM-style methods, assigning event handlers directly from JavaScript instead:
var a= document.createElement('a');
a.onclick= function() {
alert('Hello from normal JS with no extra escaping!');
};
My solution would be
addHtml('<a onclick="alert(\'Hello from JS\')">click me</a>')
I typically use single quotes in Javascript strings, and double quotes in HTML attributes. I think it's a good rule to follow.
How about this?
addHtml("<a onclick=\"alert("Hello from JS")\">click me</a>");
It worked when I tested in Firefox, at any rate.
addHtml("<a onclick='alert(\"Hello from JS\")'>click me</a>")
The problem is probably this...
As your code is now, it will add this to the HTML
<a onclick="alert("Hello from Javascript")"></a>
This is assuming the escape slashes will all be removed properly.
The problem is that the alert can't handle the " inside it... you'll have to change those quotes to single quotes.
addHtml("<a onclick=\"alert(\\\'Hello from JS\\\')\">click me</a>")
That should work for you.
What does the final HTML rendered in the browser look like ? I think the three slashes might be causing an issue .

Replace Single Quotes in Javascript or JQuery

i have an Html String in which i have some elements having single quotes.When i put this inside a $('varHtml'); Since the varHtml already contains some single quotes it qives an error, Can Somebody help me how to Escape the single quotes in the varHtml
Thanks in Advance
Thomson
If you have a HTML string in a variable, then you don't need to put it in quotes:
var varHtml = "<div id='foo'></div>";
$(varHtml);
javascript lacks something like an htmlencode to run client side. So you will have to use one of the script libraries. You can try this jQuery solution:
http://www.edentity.ca/WhoWeAre/Blog/Easy-Client-Side-html-EncodeDecode-using-jQuery.aspx
Or you could simply use a javascript string replace function like the one explained here: http://www.w3schools.com/jsref/jsref_replace.asp. Replace ' with ' or the HTML code you prefer. Reference: http://www.degraeve.com/reference/specialcharacters.php

Categories