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

Home Forums JavaScript Double quotes problem.

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
  • #44235

    I’m getting this string from a client and it can’t be modified before I get it, this is what I have to work with:
    (also I’m limited to JS only)


    How do I even assign this string to a variable to begin cleaning it and work with it? The double quotes
    mess things up.


    How do you get the string?


    I the string from another system that parses the site. Nothing i can controll.
    I put this ###_var on my page and the parser replaces it with the string.


    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).


    Yes! This solved my problem, also discovered that the string can contain */*. But I solved that myself.
    Awesome stuff, didn’t even know you could use syntax like var string = (function());

    Thanks for help Merri!

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.