0

For example in the following javascript code if you use single quotes to open document.getElementById('code').value = You'll reach a problem at window.open where you cannot use single quotes, to open it. That would close the getElementById and break the code. You also cannot use double quotes, because if double quotes are used you'll run into the same issue when putting quotes around newwindow. Are there ways around this?

   function genorateCode() {
  var account = document.getElementById("account").value;
  var url = document.getElementById("url").value;
  document.getElementById('code').value = '<link href="https://fonts.googleapis.com/css?family=Lato:300" rel="stylesheet" type="text/css"><a href="' + url + '" ' + ' onclick="window.open("' + url + '", "newwindow", "width=400,height=500"); return false;">' + '<div class="button"><img src="https://s15.postimg.org/mfpd2ki8r/icon.png" width="16">@' + account + '</div></a>';
}

(this is all put into a text area, so users can use the 'generated' code)

<textarea readonly id="code"></textarea>
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Sam
  • 11
  • 4
    Possible duplicate of [How to escape a single quote ( ' ) in JavaScript?](https://stackoverflow.com/questions/16134910/how-to-escape-a-single-quote-in-javascript) – JJJ Sep 19 '17 at 05:18

2 Answers2

0

You can try to use ` with variable interpolation ${} like in the following fiddle :

function generateCode() {
  var account = document.getElementById("account").value;
  var url = document.getElementById("url").value;
  document.getElementById('code').value = `<link href="https://fonts.googleapis.com/css?family=Lato:300" rel="stylesheet" type="text/css"><a href="${url}" onclick="window.open('${url}', 'newwindow', 'width=400,height=500'); return false;"><div class="button"><img src="https://s15.postimg.org/mfpd2ki8r/icon.png" width="16">${account}</div></a>`;
}

window.generateCode = generateCode;
<p>
Account: <input id="account" />
</p>
<p>
URL: <input id="url" /> 
</p>
<p>
Code: <textarea readonly id="code"></textarea>
</p>
<p>
<button onclick="javascript:generateCode()">
Get the code!
</button>
</p>
Mika Andrianarijaona
  • 1,619
  • 17
  • 29
0

You could use ` to surround your string, which is the button beside 1 on your keyboard, usually called backtick.

This gives you access to some other syntax, so you could do something like this

function genorateCode() {
  var account = document.getElementById("account").value;
  var url = document.getElementById("url").value;
  document.getElementById('code').value = `<link href="https://fonts.googleapis.com/css?family=Lato:300" rel="stylesheet" type="text/css"><a href="${url}" onclick="window.open("${url}", "newwindow", "width=400,height=500"); return false;"> <div class="button"><img src="https://s15.postimg.org/mfpd2ki8r/icon.png" width="16">@${account}</div></a>`;
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
Sloppy
  • 143
  • 1
  • 7