Multi line strings with Javascript
Posted May 26th, 2009 in Javascript
This post shows how to do multi line strings with Javascript. Please note that it is likely the method presented here is not part of the Javascript/ECMA standard but it does work (and has been tested by me) in Internet Explorer 6 to 8, Firefox 1 to 3 and the current releases of Opera, Safari and Chrome.
Add \ to the end of each line
It's simple... add a \ to the end of each line with nothing after it and you have a multi-line string:
var s = "abc\ def\ ghi\ jkl";
Now display the above:
window.alert(s);
which shows:
abcdefghijkl
Note that the newlines are not rendered at all, so you need to make sure the appropriate spacing or line breaks (\n) etc are present in the string.
Another approach
Another approach I found is shown below, but as far as I can tell it only works in Firefox 2+ and not at all in IE, Opera, Chrome and Safari.
var s = (<r><![CDATA[abc def ghi jkl]]></r>).toString();
This does render the line breaks so if you used window.alert on the above it would show:
abc def ghi jkl
So don't use the second approach due to lack of browser support :)
Related posts:
- Upper and lower case strings with Javascript (Tuesday, September 15th 2009)
- Substrings in Javascript with substring() (Friday, July 24th 2009)
- Substrings in Javascript with substr() (Tuesday, July 21st 2009)
- Trimming strings with Javascript (Tuesday, June 16th 2009)
- Replacing text with Javascript (Tuesday, February 10th 2009)
- Find the index of a string within a string with Javascript (Friday, November 28th 2008)

Comments
blog comments powered by Disqus