12

I've been going at this problem for a solid couple hours now and having zero luck. No clue how this is even possible; I'll try to summarize.

I'm using TinyMCE to insert new content to a DB, that content is being sent back as an AJAX response after it is inserted into the DB and then shown on the page, replacing some old content. All of that isn't really relevant (as far as I can tell) to the problem, but it serves as a background to the problem.

Anyhow, the response text has '\n' appropriately wherever the content had line breaks. I can't seem to remove those damn '\n' for the life of me. I've tried a dozen regex/replace combos with zero luck. I've verified I am not losing my mind and that the code generally works by attempting to replace other words within that string and that works perfectly fine - it just will NOT replace '\n'. Here's some code I've used attempting to replace the '\n's:

responseText = responseText.replace(/\r|\n|\r\n/g, "");

responseText = responseText.replace(Array("\r", "\n", "\f", "\r\n", "\n"), "");

Niether of those do anything to the variable. I alert it immediately after to check for changes, nada. I have no idea if it will help, but here's a snippet of an example '\n' copy-pasted that will not disappear OR change.

High School transcript</li>\n<li>SAT/ACT

As a side note, I've tried doing this via PHP before the responseText is sent back to javascript with a similar replace & regex and it does NOT work either.

Community
  • 1
  • 1
Christopher Cooper
  • 1,910
  • 4
  • 20
  • 25
  • Additional note: when dealing with special characters (i.e. `\n`, `\r`, etc.) You generally want to use single quotes`'\n'`, `'\r'` since, for most purposes, you are looking for a single character rather than a string. – David Starkey Apr 03 '13 at 20:58
  • @DavidStarkey - There is no difference between single and double quotes in Javascript. The team's style guide or personal convention should be the guiding principle http://stackoverflow.com/questions/3149192/difference-between-single-quotes-and-double-quotes-in-javascript – rinogo Feb 10 '17 at 18:23

2 Answers2

26

Are you sure it's a newline and not a literal "\n" (that is an escaped newline) ?

Try this instead: (note the double backslash)

responseText = responseText.replace(/\\n/g, "");
Mark Renouf
  • 30,697
  • 19
  • 94
  • 123
4
responseText = responseText.replace(/\n/g, "");

Don't forget to use the /g flag or else only the first one will be replaced!

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
  • Doesn't work, and is virtually the same as one I tried: responseText = responseText.replace(/\r|\n|\r\n/g, ""); Yea? – Christopher Cooper Jul 07 '09 at 01:46
  • well since you said "the response text has '\n' appropriately wherever the content had line breaks", I tried it with removing line breaks and it did remove line breaks. – Andreas Grech Jul 07 '09 at 01:51