Escaping HTML in JavaScript - javascript

When I'm building HTML in JavaScript I'm constantly escaping double quotes. E.g.
$(wrapper).append("<input type=\"text\" name=\"thingummy[" + id + "]\" data-id=\"" + data_id + "\" id=\"" + id + "_" + data_id + "\" /> <br>");
and, when there are many quotation marks, I'm constantly making mistakes over which quotes I've escaped. And I end up spending more time than I'd like fixing them.
Is there a better (quicker / safer / more legible) way of building HTML than the approach I'm using?
UPDATE
One rather important point I forgot to mention! I'm outputting this JavaScript using PHP. So, I have code like this:
echo '$(wrapper).append("<input type=\"text\" name=\"thingummy[" + id + "]\" data-id=\"" + data_id + "\" id=\"" + id + "_" + data_id + "\" /> <br>");';
which makes using single quotation marks a problem ('cos they end up breaking the PHP! Which is another problem I keep experiencing when I forget I'm in the middle of some PHP and use a single quotation mark as mentioned in a comment below).

You could perhaps use templating strings in JavaScript. Makes it simple to insert variables into a string too with ${var} syntax.
echo '$(wrapper).append(`<input type="text" name="thingummy[${id}]" data-id="${data_id}" id="${id}_${data_id}" /> <br>`);';

You could use heredoc syntax like this:
<?php
echo <<<JAVASCRIPT
<script type="text/javascript">
alert("some javascript code where you don't have to escape double quotes");
</script>
JAVASCRIPT;
This would simplify you work.
Or you can close your php tag and open it again, like this:
<?php
$somePhpCode = 1;
?>
<script type="text/javascript">
alert("some javascript code where you don't have to escape double quotes");
</script>
<?php
$somePhpCode = 2;
?>

Related

Onlick doesn't work

I'm newbie in programming. I would like to open a link by using onclick event but this doesn't work....Can you help me please?
Here the code:
$content .= '<a class="mike-link mike-pinterest"
href="'.$pinterestURL.'" data-pin-custom="true" target="_blank"
onclick="window.open("", "mikewindow","menubar=1,resizable=1,width=350,height=250");
return false;">Pin It</a>' ;
I think what you are trying to achieve is the following:
$content .= '<a class="mike-link mike-pinterest"
href="javascript:window.open("'.$pinterestURL.'", "mikewindow","menubar=1,resizable=1,width=350,height=250");
return false;" data-pin-custom="true" target="_blank"
>Pin It</a>' ;
onclick="window.open("", "mikewindow","menubar=1,resizable=1,width=350,height=250");
Your first " starts the attribute value.
Then you say window.open( which is the attribute value.
Then you say " which marks the end of the attribute value.
Then you say " again, which is invalid HTML.
If you want to include a " as data in an HTML attribute delimited with " characters then you need to encode it as "
Try this:
$content .= '<a class="mike-link mike-pinterest"
href="' . $pinterestURL . '" data-pin-custom="true" target="_blank"
onclick="window.open(\'\', \'mikewindow\',\'menubar=1,resizable=1,width=350,height=250\');
return false;">Pin It</a>';
Your problem was that you used double quotes to open the onclick, but then double quotes again inside the window.open function, which instead closed the onclick action quotes. The tricky thing is that using single quotes will close your php quotes. So what you do is use \', which lets php ignore the single quote, and write it as a single quote in your html.
Check this this codepen link:
<p>Click Me!</p>
$('p').click(function(){
window.open('https://google.com');
});
https://codepen.io/anon/pen/ZjRbEW

How can I use window.open in my string echo'd from PHP?

Through a $_POST request I query a database and return info in a string as follows:
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
My problem is the "window.open" statement. It works as follows in a plain html doc as inline JS:
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
But I think my problem in the PHP string is the single and double quotation marks.What am I doing wrong?
You need quotes around the URL.
$output .= '... <a href="#" onclick="window.open("' . $prev . '", "_blank", ...
// ---------------------------------------- here ^ -- and here ^
You would be able to notice this pretty quick if you looked at your HTML source, to see what was generated.
It seems that you've messed up the quotes in there slightly...
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
You used " to define the onclick event, however you've used " inside of that event, which made it invalid. Replace the " inside of the event with \', which will escape the quote and not mess up your PHP.
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
And, if $prev is not referring to a variable in JS (if it will end up as a string), you need those quotes around that as well.
\''.$prev.'\'

How to put linebreaks on dynamically generated javascript code

Working on ASP.net website. In my webpage I'm dynamically writing some javascript in the code-behind code. How can I put linebreaks at certain points so that if I do a 'view source' of the page it is more readable? Right now all the dynamic js code is one one line.
I've tried appending <BR/> but that doesn't seem to work.
Thanks!
<br /> is html element which will not help you at this point. you can use Environment.NewLine to add these line-breaks: example code will be like the following:
StringBuilder strBuilderJS = new StringBuilder();
strBuilderJS.Append("<script language='javascript' type='text/javascript'>" + Environment.NewLine +
"$(WireEvents_" + this.ID + ");" + Environment.NewLine +
"function WireEvents_" + this.ID + "(){" + Environment.NewLine +
" alert('stuff');");
strBuilderJS.Append(Environment.NewLine + "}</script>");
If you're using Response.Write(), you can use \r\n to add a newline in your HTML output.
Example:
Response.Write("<div>\r\nThis is my text.\r\n</div>"
This will appear in the HTML as:
<div>
This is my text.
</div>

Replace all html attribute definitions that use single quotes with double quotes

I have an html string and I want to replace any instance of an html attribute being set with single quotes with double quotes.
So for example, I want to replace
<script src='foo.js'></script>
with
<script src="foo.js"></script>
However, I want to do this without affecting any single quotes that might be in javascript statements or in text within the html.
Eg
<script> var foo = '67'; </script>
should be unaffected and
<div id='foo'> 'hi' </div>
should become
<div id="foo"> 'hi' </div>
Is there any easy way to do this?
For a given element selecting it with jquery and then reading its outerHTML does this but I want to do it to an entire page of html all at once.
Thanks!
Try this:
var str = "<br style = 'width:100px'/> test link";
var regex = /<\w+\s*(\w+\s*=\s*(['][^']*['])|(["][^"]*["]))*\s*[\/]?>/g;
var rstr = str.replace(regex, function($0,$1,$2){
return $0.replace($2, $2.replace(/'/g, '"'));
});
console.log('replaced string = ' + rstr);
You can refector it to strictly match your case.
Answering my own question as I think the easiest solution to this is what is shown in this fiddle and does not require jquery or regexps:
http://jsfiddle.net/QdUR5/1/
<html id="foo"></html>​
var htmlString =
'<head>' +
'<script type="text/javascript" src=\'main.js\'></scr' + 'ipt>' +
'</head>' +
'<body onload=\'onLoad()\'>' +
'</body>' ;
document.getElementById('foo').innerHTML = htmlString;
console.log(document.getElementById('foo').outerHTML);
​
Basically you just need to set the inner html of an html element to the html string without the html tags and then output the html elements outer html.
I think that is a bit simpler than using a regexp although that is an awesome regexp Mike :)

How to escape a single quote in jQuery?

I know I can use \', but that's not the point here. Let's say I have the word "can't". It has "'" in it now. This goes in to a var in a function like so:
function active(id,clas,match,hometeam,awayteam){
So let’s say hometeam has the value of "can't". When I try to use this code:
$('#test').html(hometeam + " VS " + awayteam);
It's not working, because essentially it has:
$('#test').html(can't + " VS " + awayteam);
How do I solve this?
EDIT:
I think the problem is not in the jQuery. The line that calls this function is this line:
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','match1','hometeam','awayteam')" />
So how do I escape this?
EDIT: I haven't found the perfect solution, so I just changed the word in my database and added the "\" for now...
This should work. If the contents have double quotes then wrap the string in single quotes and escape single quotes inside.
var hometeam = '"can\'t"';
$('#test').html(hometeam + 'VS' + awayteam)
The values returned by variables do not need to be escaped in javascript. If you are having a problem there is some other underlying issue.
EDIT: Per your question edit you will need to escape the value in the function call, if you were to use can't as one of your parameters you would need
<input type="button" id="btn" value="1.4" class="butta" onmousedown="active('btn','buttdowna','can\'t','hometeam','awayteam')" />
The problem is that you are using string operations to build HTML. Use jQuery/DOM methods instead and you won't have issues with this.
Another way would be escaping the quotes but compared to the previous suggestion that's just really ugly.
Since you are creating the HTML in PHP, do something like this:
echo '<input type="button" id="btn" value="1.4" class="butta" onmousedown=\'active("btn","buttdowna","match1",'.htmlspecialchars(json_encode($foo)).', '.htmlspecialchars(json_encode($bar)).');\' />';
You can change the HTML Part like this it will work,
<input type="button" id="btn" value="1.4" class="butta" onmousedown=active("btn","buttdowna","match1","can't","awayteam") />
In an HTML attribute without Quotation also work. Quotation is used to group. Example) title="Click Event" will work and title=Click Event will take the first value(Click) only. That is if a word doesn't contains space then no need of Quotation.

Categories