JavaScript escape from multiple quotes - javascript

I'm basically trying to put this.name instead of "main" tag. Could not find a way to do it on javascript since quotes messes it up.
Code:
document.querySelector('button[name="main"]').classList.add('selected');

try :
document.querySelector('button[name='+this.name+']').classList.add('selected');

Just check
var obj = document.querySelector('button[name="main"]');
alert(obj);
It is working, the problem is in you classlist.add('selected') part

Related

How to add single quote "'" to javascript string

So many related questions out there, but none satisfyingly answered using javascript (no jQuery).
I wish to add quotes around a variable in a string I'm building. My string itself should contain single quotes within it like so:
'{'a'}'
I can get:
'{a}'
When I try to add single quotes around the key a I get:
'{\'a\'}'
I've used both of the following syntax with the same result.
Any suggestions??
concat('\'','a','\'')
'\''+'a'+'\''
See line 39 of this code: https://repl.it/#mike_butak/LiveForHisPleasureHeReallyIsThere
Thanks!
Like this?
console.log("'{'a'}'")
To expand on this, when you are building the string, just use " around the string, and ' within the string.
Having a hard time replicating your issue! See:
var temp = '\'{\'a\'}\'';
console.log('s' + temp + 's');
I'd definitely recommend demonstrating the issue you are asking about in a console print or in a readily available editor online before posting a question!
As per your comment, updating to make it part of a variable assignment. Still unclear what the issue is!

Trying to append html string fail with jQuery

I'm trying to append the following string to head with jQuery :
"<script type='text/javascript'> window['adrum-app-key'] = 'dummy';</script>"
But it always fails. Trying to do the same with 'Hello' string for example works as expected.
Following the code snippet I use to append the string :
var integrationScriptTag = handlebars.partials.integration(integrationData);
$(document).ready(function() {
$('head').append(integrationScriptTag.trim());
});
First string is the result of parsing integrationData.
Any help will really be appreciated.
Edit: I realize I misguided some of you with the first string. It is just a representation of what is produced by the first line of the second code snippet. So it doesn't really matter if it is some quote marks or not. The fact is I don't use a literal but rather a variable which is equal to the first string. I corrected the syntax so that there is no more confusion.
Here is the jsFiddle reproducing the problem.
jsFiddle
This should fix it:
'<script type=\'text/javascript\'> window[\'adrum-app-key\'] = \'dummy\';</script>'
or this would too:
'<script type="text/javascript"> window["adrum-app-key"] = "dummy";</script>'
Essentially you have quotes mismatch.
Use this, it will fix the issue
'<script type=\'text/javascript\'> window[\'adrum-app-key\'] =\'dummy\';<\/script>'
I finally found that you cannot append script tags to head with jQuery this way.
I found some solutions here and there (look at the first code snippet of the selected answer for the second link).
The head is parsed prior to the execution of javascript. So you probably have to perform the append outside the $(document).ready function.

javascript code error shows undefined value

function abc(id, name){
var button = '<img src="/images/abc.png" onclick="getvalue('+id+','+name+')"/>';
$('Div1').set('html',button);
}
my this code is not working. it gives an error.
The error is: suppose value of name is Gaurav. then it gives error Gaurav is not defined.
Please help me and tell me where is error.
That is because you are generating code that uses the string value without delimiters.
If id is 42 and name is Gaurav, you will generate the code getvalue(42,Gaurav) instead of getvalue(42,'Gaurav').
Put apostrophes around the string in the code:
var button = '<img src="/images/abc.png" onclick="getvalue('+id+',\''+name+'\')"/>';
Note that this only works as long as the string values doesn't contain any characters that need encoding, like apostrophes or auotation marks.
You need quotes around name and id.
var button = '<img src="/images/abc.png" onclick="getvalue(\''+id+'\',\''+name+'\')"/>';
You need to enclose the function arguments in quotes:
var button = '<img src="/images/abc.png" onclick="getvalue('+id+',\''+name+'\')"/>';
By omitting the quotes, you are passing the undefined variable Gaurav in as an argument to the function. What you really intend is to pass in the string "Gaurav" rather than a variable.
Quotes around id may also be necessary:
var button = '<img src="/images/abc.png" onclick="getvalue(\''+id+'\',\''+name+'\')"/>';
The error likely occurs on the call to getvalue as you are supplanting the value of name and not passing a reference. In essence when the code is emitted it would read...
<img src="/images/abc.png" onclick="getvalue(something, Gaurav)" />
Which will cause a problem for the javascript engine as it has no idea what Gaurav is.. try quoting the value..
var button = '<img src="/images/abc.png" onclick="getvalue(\''+id+'\',\''+name+'\')"/>'
Which will render something to the effect of..
<img src="/images/abc.png" onclick="getvalue('something', 'Gaurav')" />
You should mention what the intent of the code is, as it's not completely clear. I'm guessing that it takes the id and name, and dynamically creates an image. I'm not sure if you're using jQuery or not, since I see the use of "$".
Setting the click handler in this way, with string concatenation, is not as safe as doing it programatically. You can easily run into code injection issues with your original approach. e.g. if the name has the word "O'Reilly" in it.
If you're using jQuery, you can do something like this:
var button = $('<img src="...">').click(function() { getvalue(id, name); });
You can find more examples here: http://api.jquery.com/click/

Hyphen in div id causing javascript error

I'm having an issue with javascript whereby i am performing the following to close a popup window and update a field in the parent window with the required value. Code looks something like this:
<script language="javascript" type="text/javascript">
var FieldID = document.form.field22-1.value;
self.parent.opener.document.+FieldID = 'some text';
window.top.window.close();
</script>
However I am getting the following error:
Error: missing ; before statement
I have a funny feeling the javascript is interpreting the field id (field22-1) as having a subtraction in it. Which I guess would make sense. Any ideas/help would be ridiculously appreciated, really don't want to have to go back in and change the - in the code!
Thanks in advance!
Use document.getElementById('field22-1').value instead.
You might also need to fix this:
self.parent.opener.document[FieldID] = 'some text';
In JavaScript, any property of any object can be accessed either via dot notation, e.g. foo.bar, or bracket notation, e.g. foo["bar"]. The latter is necessary when your property is not a legal identifier (as in your case):
var FieldID = document.form["field22-1"].value;
Alternatively, if this is an actual id attribute, you should use:
var FieldID = document.getElementById('field22-1').value;
You could also use document.form['field22-1'].value.
You can use document.getElementById('field22-1').value

Escaping dilemma in Javascript

I have the following
var id='123';
newDiv.innerHTML = "";
Which renders in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
newDiv.innerHTML = "";
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
There is no good excuse for gluing strings together in Javascript
All it does is ADD overhead of html parsing back into dom structures, and ADD potential for XSS based broken HTML. Even beloved google get this wrong in some of their advertising scripts and have caused epic failures in many cases I have seen ( and they don't want to know about it )
I don't understand Javascript is the only excuse, and it's NOT a good one.
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
You should be using " not " or \" inside an HTML string quoted with double-quotes.
NewDiv.innerHTML = "";
There's probably a better way to do this - any time you find yourself using eval() you should stand back and look for a different solution.
You claim that eval is the right thing to do here. I'm not so sure.
Have you considered this approach:
and in your StepTwo function
function StepTwo(func,args,flag){
//do what ever you do with the flag
//instead of eval use the function.apply to call the function.
func.apply(args);
}
You could create the a element and attach to the click event using DOM Methods.
A Javascript Framework (like the ubiquitous jQuery) would make this a lot easier.
Your biggest problem is using eval, it leads to so many potential problems that it's nearly always better to find an alternative solution.
Your immediate problem is that what you really have is
as the next " after the start of the onclick attribute, closes it. Use " as others have suggested. And don't use eval.
You need to alternate your " and '.
Maybe you don't need quotes around the 123, because of Javascripts flexible typing. Pass it without quotes but treat it as a string within TestFunction.
Hey guys, thanks for all the answers. I find that the quot; seems to work best.
I'll give you guys some votes up once I get more reputation!
In regards to eval(), what you see in the question is a very small snapshot of the application being developed. I understand the woes of eval, however, this is one of those one in a million situations where it's the correct choice for the situation at hand.
It would be understood better if you could see what these functions do (have given them very generic names for stackoverflow).
Thanks again!
The best way is to create the element with document.createElement, but if you're not willing to, I guess you could do or use ".
In your code:
newDiv.innerHTML = "";
If it doesn't work, try changing "\'" to "\\'".
Remember that the " character is used to open and close the attribute on HTML tags. If you use it in the attribute's value, the browser will understand it as the close char.
Example:
<input type="text" value="foo"bar"> will end up being <input type="text" value="foo">.
...
I know this is hella' old now, but if anyone has issues with escaped strings when using eval (and you absolutely have to use eval), I've got a way to avoid problems.
var html = '';
eval('(function(div, html){div.innerHTML = html;})')(newDiv, html);
So, what's going on here?
eval creates a function that contains two parameters, div and html and returns it.
The function is immediately run with the parameters to the right of the eval function. This is basically like an IIFE.
In this case
var myNewMethod = eval('(function(div, html){div.innerHTML = html;})');
is basically the same as:
var myNewMethod = function(div, html){div.innerHTML = html;}
and then we're just doing this:
myNewMethod(newDiv, html); //where html had the string containing markup
I would suggest not using eval. If it can't be avoided, or if you control all the inputs and there's no risk of injection then this will help in cases where string escapes are an issue.
I also tend to use Function, but it isn't any more secure.
Here's the snippet I use:
var feval = function(code) {
return (new Function(code))();
}

Categories