At witt's end… Javascript won't replace '\n'!

白昼怎懂夜的黑 提交于 2019-12-10 02:04:34

问题


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.


回答1:


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, "");



回答2:


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

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



来源:https://stackoverflow.com/questions/1089925/at-witts-end-javascript-wont-replace-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!