A JavaScript Trick You Should Know

JavaScript Strings

You should know that in JavaScript you cannot simply write a multilined code chunk, i.e. something like this:

var str = 'hello
world';

This will result in an error, which can be a problem when you deal with large strings. Imagine a string containing some HTML that should be injected via innerHTML. Now one possible solution is to concatenate two or more strings, by splitting the initial string.

var str = 'hello'
        + 'world';

Howerver this solution result in some additional operations like concatenation. It can be very nice if there was something like the PHP multiline string format.

The PHP Example

In PHP you have the same use case with strings. You can have a string concatenated over multiple lines, but you cannot split lines like so:

// the following line is wrong
$str = 'hello
world'; 
 
// a possible solution to the line above is
$str = 'hello'
     . 'world';
// which is very similar to the js solution in the second example
 
// ... but in PHP there is the so called HEREDOC
$str = <<<EOD
hello
world
EOD;

The heredoc gives us the power to write multiline strings.

The JavaScript Trick

Actually in JavaScript there is something that’s exactly what Heredoc is meant to be for PHP. Take a look at the last example:

var text = <>
this <br />
is
my
multi-line
text
</>.toString();
 
document.body.innerHTML = text;

Thus you can write multiline strings in the JavaScript code.

4 thoughts on “A JavaScript Trick You Should Know

  1. Incorrect.

    This is using a Firefox only E4X pattern.
    Do not teach people this fairly useless technique.

    var string = “Hello\n\
    I’m a\n\
    Really\n\
    Multiline\n\
    String”;

    Try the above.

    This will work regardless of browser.
    (The “trick” here is the end \ is escaping the new line. Genius).

  2. Here’s another idea: if you have a large, multi-line string, just put it inside a script tag.

    <script>
    Hello
    I'm a 
    Really
    Multiline
    String
    </script>

    And then you can get it from javascript like this (example is in jQuery):

    var string = $('#example').html();

    This has the added benefit of locating all your long strings (templates, etc.) in a better place — the markup!

    Roy

  3. Darn, it killed my script tag. Trying again using square brackets instead of angle brackets:

    [script type="appresources/string" id="example]
    Hello
    I’m a
    Really
    Multiline
    String
    [/script]

Leave a Reply

Your email address will not be published. Required fields are marked *