Javascript line break rendering confusion
This is something that I know I will forget each time I run into it, so it's going up here for reference!
I use Javascript a fair bit, not as an advanced user but for everyday things like validation and moderate UI dynamic modifications. I was recently returning a string value from a remote ColdFusion function directly to a Javascript callback function then displaying it via alert() to the user. The string I returned contained "\n" characters in it so that I could control where the line breaks were to be when the alert function displayed it in a pop-up. What I wasn't counting on was that javascript would ignore these line breaks and simply display the "\n" string along with the rest of the message in one clump of characters all on a single line!
I figure, and please correct me if I am wrong, that since the string was created by ColdFusion as just that, a string, Javascript is not recognising the line breaks. If however, I was to create the exact same string in Javascript containing the same "\n" characters, it would indeed render correctly placing the line breaks where they have been indicated. Javascript seems to escape the \n values in the string passed by ColdFusion (like so: "\\n") and therefore negates the line break values.
Example:
ColdFusion returns the string: "Line one\nLine two\nLine three" and I would expect this to appear in an alert popup box as:
Line one
Line two
Line three
However the Javascript alert instead displays it as:
Line one\nLine two\nLine three
To fix this I had to use a Javascript global replace fucntion on the escaped characters in the string:
var newString = returnedString.replace(/\\n/g, '\n');
alert(newString);
Note that you have to use the "g" value in the above replace line. It stands for global - this way you replace all instances in the string and not just the first.
And that's that.


