Triple quoted strings

liorean liorean at gmail.com
Thu Mar 6 05:21:02 PST 2008


On 06/03/2008, P T Withington <ptw at pobox.com> wrote:
>  I'd like to see us keep triple-quoted strings.  But with a simpler
>  (tried and true?) syntax, say that of Python 'long strings'.  (Which
>  to my mind are just heredocs without a choice of delimiter.)  Seems to
>  me we just tried to be too clever parsing triple-quoted strings,
>  leading to all those funny edge cases that started this thread.

Is the current syntax so bad, then, or complicated? The treatment of
the string content itself is basically the same as for any other
string with the single exception of newlines being allowed. The
external syntax seems like it would match this regex:

    /((["'])\2\2)((?:\\[\s\S]|(?!\1(?!\2))[\s\S])*)\2/

(Hmm. Were there any proposal for adding a any-includes-newline flag
or a any-including-newlines escape instead of the [\s\S] cludge? If
not, is \A)

I don't see it being such a bad idea - it's just syntactic sugar over
normal ES3 strings. Just to prove the point, transforming such a
string to the equivalent ES3 can be done like so:

    var
        reTripleQuotedString =
/((["'])\2\2)((?:\\[\s\S]|(?!\1(?!\2))[\s\S])*)\2/,
        es4TripleQuotedString='"""some\nstring" \'\'\'with "" several
\\""" different quirks\\\n\n\'\'\' in it """""',
        match=reTripleQuotedString.exec(es4TripleQuotedString),
        delim=match[2],
        reDelim=new RegExp(delim,'g'),
        contents=match[3],
        es3String=delim+contents.replace(reDelim,'\\'+delim).replace(/\n/g,'\\n')+delim;

    // es4TripleQuotedString => """some
    //string" '''with "" several \""" different quirks\
    //
    //''' in it """""

    // es3String =>"some\nstring\" '''with \"\" many \\"\"\" different
quirks\\n\n''' in it \"\""



Sure, we could have wanted a more advanced string building mechanism
that was literal all the way, without ES3 escaping. Or we could have
wanted a more dynamic string that expanded expressions in it using
some syntax. Or we could have wanted a user selectable delimiter.

But for the use case of not having to make multiline strings instead
be long strings containing \n where there is conceptually a newline,
and for the use case of not having to escape singly quoted delimiters
in the string, what we have is good enough. I think we should keep it
as-is.
-- 
David "liorean" Andersson



More information about the Es4-discuss mailing list