1

There is a lot I don't like about PHP, but one thing I love is multi-line strings:

$query = <<<EOT
select
     field1
    ,field2
    ,field3
from tableName
where
    field1 = 123
EOT;

What's cool about this, is that I can just copy SQL, that I've hand formatted (to my liking) from a querying tool (like dbeaver), and paste it (with formatting and all) directly into a php script, without worry about how line-breaks might corrupt the script.

There's a lot I love about Javascript, but there doesn't seem to be a reliable equivalent that would allow you to copy and paste a pre-formatted SQL statement into a variable-value (with this same ease -- and preserving the formatting).

I'm currently working on some small node.js projects and I'm very much missing this php feature.

The only think I can think to do, is to put my queries into a plain text file and import the formatted query from a file into the variable value. Then, later, when I need to modify the query, I can copy and paste to that file (pre-formatted) and then the script will just load my modifications next run.

However, sometimes I need certain parts of the query to be dynamical generated. In PHP, I could put variables into the multi-line string for such requirements. With this separate file idea (in Javascript), it seems more complicated; I'd have to make custom place-holders in the plain text file that are to be replace by the main script later. That seems like I might be reinventing a wheel that is already made. So that's why I'm posting here for advice.

I've read other post that have hacks for doing this type of thing in-script, but each solution doesn't match the ease and reliability of php's built-in support for such requirements.

5
  • 1
    Creating multiline strings in JavaScript Commented Feb 25, 2015 at 20:37
  • Yeah, I've read that. I'm just not quite satisfied with any of those answers. Right now, I'm just putting the query in a separate plain-text file, and loading it into the variable via the fs module. Commented Feb 27, 2015 at 19:53
  • I think that's about the best you're gonna get in Javascript. Commented Feb 27, 2015 at 20:51
  • Yeah, I'll use this technique until ECMAscript 6. The desired feature is coming: nczonline.net/blog/2012/08/01/… Commented Feb 27, 2015 at 22:12
  • This article addresses exactly what I'm looking for (coming in ECMA 6). Commented Apr 2, 2015 at 6:16

1 Answer 1

0

JavaScript now supports multi-line strings via the backtick sytax. For example:

const foo = `$query = <<<EOT
select
     field1
    ,field2
    ,field3
from tableName
where
    field1 = 123
EOT;`

References

1
  • Did you read my comments above (from 2015)? Commented Aug 20, 2018 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.