Affichage des articles dont le libellé est multiline. Afficher tous les articles
Affichage des articles dont le libellé est multiline. Afficher tous les articles

jeudi 9 octobre 2014

JavaScript multiline code (JSON description)

It is currently not possible to store a multiline string in javascript. This is annoying since for example storing some JSON data often leads to long data to concatenate or to push into an array.
If you want to avoid this, you can use the following trick, since javascript accepts multiline comments, and returns them to the toString call on a function :

var jsonDescriptionText= function(){/*
[
    {
        "cat": "Categ1",
        "links": [
            {
                "txt": "text1",
                "url": "http://url",
                "title": "mouseover field"
            }
        ]
    }
]*/}.toString().slice(14,-3);
Note 1 : This avoids using concatenation for each line :
var longString2="string part1" + 
"string part2" 
or even escaping the new lines :
var longString2="string part1\
string part2"

Note 2 :

ECMA-262 5th Edition section 7.8.4 and called LineContinuation : "A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as \n or \u000A."

Note 3 :
 "In EcmaScript 6, you'll be able to use backticks for Template Strings, known in the spec as a NoSubstitutionTemplate:
var htmlString = `Say hello to 
multi-line
strings!`;
 "


(seen on : http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript)