JavaScript regex-to-string conversion



  • I was working on a Django-based website, and needed to get the URL for static content (images, etc) from JavaScript.
    I added the lines

    <script>
    var static_url = {{STATIC_URL|escapejs}};
    </script>
    <!-- other scripts needing static_url here ... -->```
    in my Django template file. It seemed to work fine; the scripts generated correct URLs.
    
    Then I deployed the website on a dev server (instead of running it on my machine), and... things died horribly.
    
    I looked into the generated page and saw:
    ```html
    <script>
    var static_url = http://blahblablah/static/;
    </script>
    

    OK, so I did a mistake in the template; the |escapejs filter escapes any quotes when substituting the template variable, but does not put the variable itself between quotes. I should have used

    var static_url = "{{STATIC_URL|escapejs}}";```
    
    But... *how did it work on my machine?*
    
    Well, on my machine, ```STATIC_URL``` was just the string “/static/”. So the JavaScript parser saw
    ```javascript
    var static_url = /static/;```
    and interpreted it as a regular expression.
    
    And when the other JS code did things like ```var image_url = static_url + "some_image.png";```, the value was silently cast  to the string “/static/” (with the slashes), so everything worked in the end.
    
    I was already convinced that JS’s ability to parse /something/ into a regex was a bad idea (mostly because /* is the start of a comment, so there may be some parsing confusion), but now...


  • @VinDuv said:

    I was already convinced that JS’s ability to parse /something/ into a regex was a bad idea (

    I prefer a literal regex notation over regex-in-a-string, actually. It means I never have to think about whether I'm escaping this char because of the string or because of the regex or maybe I should double-escape that plus, or type three extra backslashes before a backslash or aaaaargh. So yeah. A regex literal instantly removes all of that ambiguity.



  • Or at least the sort of string that doesn't require special escaping.



  • @dhromed said:

    It means I never have to think about whether I'm escaping this char because of the string or because of the regex or maybe I should double-escape that plus, or type three extra backslashes before a backslash or aaaaargh

    I agree that new RegExp("...") is troublesome. Most scripting languages provide a way to define raw strings, which are not parsed for escape characters (r"..." in Python, '...'in PHP and Perl), but not JavaScript, AFAIK...



  • I remember helping someone with a bizarre regexp in PHP that required 13 backslashes in the end.



  • It was searching source code for escape sequences in regexes embedded in string literals?



  • @VinDuv said:

    (mostly because /* is the start of a comment, so there may be some parsing confusion)

    Thankfully we can get away with that, because starting a regex with * would be an illegal expression. But for people writing syntax highlighters, yes, they have to be veeeeerrrry careful.



  • How to print strange unicode character using JavaScript?



  • You can use literals in the format \uHHHH much like Java. Example:

    > var f\u006F\u006F = 'abc';
    > foo
    'abc'

    > var λ = 123;
    > \u03BB
    123

    Filed under: Jeff recommends you search StackOverflow first



  • Are you making use of node.js?



  • Nope. I'm not as crazy as @codinghorror. I'll stick with compiled, strongly-typed languages that support threading.



  • I like Javascript. Live fast, die dangerously. You can always use Typescript, if you want typing, of course.

    Cue Typescript rant in .. 3 .. 2 .. 1 ..



  • @TGV said:

    I like Javascript. Live fast, die dangerously. You can always use Typescript, if you want typing, of course.

    Cue Typescript rant in .. 3 .. 2 .. 1 ..

    Tried it once. Everything is great while you're playing around. Then you decide to do some real work and try to import your favorite JS library. Suddenly, everything turns red and your nice static typing is useless.

    You then learn there are such things as type definition files, most of which are maintained by TS enthusiasts in their spare time. You download one of these files for your specific library. Some of the red goes away, but some remain. You're using a newer version than the definition file. Oh well, you can live with a few red squiggles. You try another library, but it's the same thing. The red squiggles multiply.

    So you start hacking away at definition files, hoping to fill in the holes. It's a bit boring, but not too bad. Pretty soon you're done and all the red squiggles disappear. You wasted some time, but you figure you'll make up for it with greater productivity and joy in coding. As you go on with your project, everything is fine with the world...

    ... until the next time an update for your JS libs come out. Damn, the red squiggles are back. Sigh, it's back to hacking the definition file for you.

    As you incorporate TS into more and more projects, there are more and more TS definitions to fix. Red squiggles are everywhere. You stamp them out, but they always come back. You join the TS map file community and start contributing. If we all work together, we can win, guys! I know we can!

    But the red squiggles are persistent. Ceaselessly they keep coming back. More extreme action is required. You take a sabbatical from work. You can make up for the lost time once everything is converted to the beautiful static typing. Oh, look, a new popular JS library just came out and d.ts files are out of sync again. You lock yourself in and hunt the squiggles.

    Alas, new libraries keep coming. There are millions of javascript devs producing untyped code and just the few of you believers, trying to cover them all. The more you stamp, the more red squiggles they are. Almost as if... they are mocking you? Teasing you? You type faster, ignoring the ringing phone. No time! Clean statically typed web is within your grasp!

    Wiggles squiggles. Always coming. Always wiggling. Little fiends, dancing through your code. Over your monitor, over the walls. Over the bottles where you keep your urine and measure its viscosity. You stamp and stamp and stamp. Stampy stamp crackety crack! The door cracks open. Who are these men in white coats? Are they with the squiggles? No! They are dragging you away! But you were so close! So close to perfection of the clean, beautiful, statically typed web! Don't you see! Don't you all see what could have been!? Nooooo!

    ...

    Or you could just decide it's too much work dealing with this shit and go back to plain old javascript. Like I did.



  • I read faster and faster as I went through this rant. Excellent. Would read again.


  • BINNED

    +41

    Because clicking the like/undo like links 42 times fails to reproduce the result.



  • @cartman82 said:

    Wiggles squiggles. Always coming. Always wiggling. Little fiends, dancing through your code.

    Great writing. Inspired, even. No doubt inspired by frustration.

    I actually use Typescript sometimes, but for something that doesn't require an external library, but has to run in a browser, 'cause reasons. Typescript is a neat idea, but not for web development.



  • I like the way @cartman82 is describing the wiggles. Making me think of cartoon network.



  • What people don't realize is that we need something to replace JavaScript, not another framework or library or whatever to go on top of it, next to the eleventy billion others that we already have.


  • BINNED

    @chubertdev said:

    What people don't realize is that we need something to replace JavaScript

    "Hey, that's cool. But you know what it needs? <Feature X>! What? Language designers won't add it? Fuck it, fork the damned thing, let's do this!"

    "Hey, that's cool. But you know what it needs? <Feature Y>!"

    Error: Too much recursion.


    Filed under: Not saying you're wrong, but you know I'm right too



  • They will never stop making new frameworks and claiming that this is the best framework ever.

    I am mustache.js developer.
    Fk mustache.js, knockout.js is 10 time better.
    S
    *w knockout.js, Sproutcore is best thing evah

    Till we get to this situation.

    I am thinking, why use just 20 frameworks, use 40. For fun, just use all framework on single webpage and confuse the poor developer who then develop stress and leave job.


  • BINNED

    Correction: mustache.js is not a framework, it's just a JS implementation of the mustache templating engine parser.

    And I'm actually using it, because it's implemented in a bunch of languages. Including PHP so I can render my templates both serverside and clientside with identical results (+/- an edge case).

    I think there was some talk about Discourse using HTMLbars. Which was build on top of handlebars. Which in an extension of mustache that adds some logic into templates. While the main "selling point" of mustache is that it's logicless...


  • Discourse touched me in a no-no place

    You can't beat that game, but you can join in the winning side. Make your own framework, then sell consultancy on it.





  • @Onyx said:

    I think there was some talk about Discourse using HTMLbars. Which was build on top of handlebars. Which in an extension of mustache that adds some logic into templates. While the main "selling point" of mustache is that it's logicless...

    So we're just piling more crap on top of a bad language, and becoming more dependent on it. Great.


  • BINNED

    @chubertdev said:

    So we're just piling more crap on top of a bad language, and becoming more dependent on it. Great.

    I don't think mustache is bad by itself. Overly simplistic at times? Maybe. But it does what it intended: only "logic" in the template itself is using {{#value}} and {{^value}}.

    Basically if exists (or is true) and if doesn't exist (or is false). {{#value}} also doubles as a foreach if you give it an array.

    It sounds confusing but it's not once you wrap your head around it. And it indeed forces you to get your data straight in the backend instead of piling up ifs mixed with your HTML.

    Now, piling shit on top of it, yes, I agree that's stupid.



  • @Onyx said:

    I don't think mustache is bad by itself. Overly simplistic at times? Maybe. But it does what it intended: only "logic" in the template itself is using {{#value}} and {{^value}}.

    Oh, it could be insanely awesome, but it's still part of the problem, not the solution.


  • :belt_onion:

    @cartman82 said:

    hunt the squiggles

    SquiggleHunter2000 :squirrel:



  • Awesome rant. Needs more Tony the Pony.



  • @LoremIpsum said:

    Thankfully we can get away with that, because starting a regex with * would be an illegal expression.

    Looking for a regexp that matches 0 or more slashes.

    ◀ var rex = //*/;
    SyntaxError: syntax error
    
    ◀ var rex = /(/)*/;
    Exception: unterminated parenthetical   (on Firefox)
    SyntaxError: Unexpected token )         (on Chromium)
    
    ◀ var rex = /[/]*/;
    ▶ undefined
    ◀ rex
    ▶ [Object RegExp]
    ```I'm surprised the previous one didn't work while this last one did.
    It's too much 4 in the morning for me to figure it out.
    
    <i>Addendum: well duh, I can't use unescaped slashes inside a RegExp literal except inside [ ].
    This works:
    ```js
    var rex = /(\/)*/
    ```I don't even need the parens:
    ```js
    var rex = /\/*/
    
    @Onyx said:
    +41

    Because clicking the like/undo like links 42 times fails to reproduce the result.

    Well obviously. You should click 40+40+1, ie 81 times.



  • @another_sam said:

    Awesome rant. Needs more Tony the Pony.


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.