The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Double quotes problem. Re: Double quotes problem.


Sounds odd if there is no option for escaping the quotes! Anyway, lets solve the issue.

If you’ve tried to do something like this: `var string = “###_var”;`

Then things don’t work as you’ll end up with `var string = “,”;`

The first idea most people get here is to add the data in HTML and then read the value using JavaScript:

HTML: ``

JavaScript: `var string = document.getElementById(‘myvar’).innerHTML;`

But this has two downsides. One, what if the data contains a < or > character? Something in the data could break the HTML. In the other hand you may not want put this stuff to HTML in the first place.

So can we do better? Can we put it directly into JavaScript? Yes!

var string = (function(){/*###_var*/}).toString().substr(14).replace(/*/}$/, ”);

var string = (function(){/*,*/}).toString().substr(14).replace(/*/}$/, ”);

You probably wonder what is happening here. The nice thing about JavaScript is that you can get the full string source of any function by calling `.toString()` on it. So here we create anonymous function with a comment in it, put data within that comment and then simply remove anything that isn’t inside the comment. Variable `string` then contains the data you want and that data can be almost anything (the only thing it can’t contain is `*/` which would terminate the JavaScript comment).