简体   繁体   中英

Javascript Newline Character Throwing Error

I am having trouble getting some data from a textbox using javascript. What I am trying to do is take the value from a textbox and put it in an alert and copy it. Here is the code that I currently have:

var copyString = "Date: <%= TXT_Details_DateReq.Text %>;
window.prompt('Press CTRL+C, then ENTER\n\nNOTE: SAVE ANY CHANGES BEFORE COPYING TEXT!', copyString); return false;

So this code works perfectly fine if the text in the textbox is just one line. But if the text in the textbox has multiple lines such as:

"This is one line
here is a second line"

The code will throw the error Uncaught Syntax Error: Unexpected Token ILLEGAL . From what I have researched this throws when there is an illegal character, so I believe it is the CRLF character from the textbox.

Any idea how to fix this?

Thanks.

New line characters might be preceded by return characters ( '\\r' ).

Swap '\\n' with '\\r\\n' and you should be good to go.

Or even better: just handle all cases of the new line character instead of checking which case then applying it. This replace the newline:

htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");

Resource

hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM