2

Any time I use \n anywhere in javascript/jQuery the browser throws

uncaught syntaxerror: unexpected token illegal

I found ways to work around adding new lines without using \n, but I can't find a work around to read the \n from a textarea without using \n. I am using a mac pro mavericks with the chrome browser version 36. The code is output from a php script from a linux server. I have also tried in firefox and get an equivilent error. Examples include:

var line = $('#textareaid').val().split("\n");
var line = $('#textareaid').val().split("\r\n");
var some = "This is\nsome text";

All of the examples have the error as well as any other use of \n. I have been unable to find any reference to \n not working, but plenty of examples of its use.

Machavity
  • 30,841
  • 27
  • 92
  • 100

3 Answers3

3

try this-

var line = $('#textareaid').val().split("\\n");
Cute_Ninja
  • 4,742
  • 4
  • 39
  • 63
  • This is exactly how I did it and now works. I thought I had tried like this before, but the doctype was messing it up. Thanks. – user3830357 Aug 21 '14 at 20:54
1

There is nothing wrong with "\n" in JavaScript, but if your PHP is script is printing literal line breaks, your JavaScript will be invalid.

This PHP:

echo "split(\"\n\")"; 

Will print this:

split("
")

Which would raise a JavaScript syntax error.

So the PHP should be:

echo "split(\"\\n\")";
Tim
  • 8,036
  • 2
  • 36
  • 52
0

As '\n' is an escape sequence so you have to use an additional backslash as shown below:

$('#textareaid').val().split("\\n");
Viswanath Donthi
  • 1,791
  • 1
  • 11
  • 12