Grow your CSS skills. Land your dream job.

Double quotes problem.

  • # April 19, 2013 at 12:50 am

    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.

    # April 19, 2013 at 7:08 am

    How do you get the string?

    # April 20, 2013 at 9:32 pm

    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.

    # April 21, 2013 at 12:30 am

    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(/*/}$/, ”);

    // BECOMES THIS:
    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).

    # April 22, 2013 at 5:25 am

    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)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".