One of the most loved python language features is multiline strings. In JavaScript there is actually no support for multiline strings. But by doing some tricks we can get this feature. In this post I will show you three different ways to get this feature in JavaScript.
What is Python Multiline Strings
Python multiline string(or block string) is a string which is spread over multiple lines and also new line characters are preserved. A python multiline string looks like this:
Multiline string In JavaScript
There are basically two native methods and one hacked method.
Method 1
Using the “\” character. Actually “\” character allows us to spread the string over multiple lines but it doesn’t preserve new line characters. Therefore if you are using this method then remember to put new line characters manually. So we can say “\” allows us to create line concatenated string.
JS Bin
Method 2
We can use ECMAScript 6 Template String to achieve the same type of multiline string as python.
JS Bin
Many browsers don’t yet support ECMAScript 6 therefore the above example may not work.
ECMAScript 6 template string also support string substitution feature as shown in the above example.
Method 3
This is basically a hacked way of getting this feature. This method converts JavaScript comments into multiline string preserving the new line characters.
Let’s see an example of this:
JS Bin
You can also achieve string substitution using more advanced regular expression functionality.
This is my favorite method and is very compatible. I don’t use this feature from scratch instead I use a library called as JavaScript multiline which provides the same.
One major problem with this method is JS minifiers remove javascript comments. But you can stop them from removing these special comments by this way:
- Uglify: Use /*@preserve instead of /* and enable the comments option
- Closure Compiler: Use /*@preserve instead of /*
- YUI Compressor: Use /*! instead of /*