简体   繁体   中英

Replacing newline in multiline textbox with <br/>

I am trying to use a multiline textbox to insert text into a table which is displayed as html. I want to with javascript take the text inside of the textbox and find where the user pressed enter and place " <br/> " in that position so when the text is displayed it will show line break. Any ideas on how I could do this?

I tried something like this but it did not work.

var text = document.getElementById("announcementid").value;


            var newtext = text.replace("\n", "<br/>");

            text = newtext;

The newtext variable ends up being a copy of the original string from your announcementid element. Thus, you'll need to re -set the value property on the original document element:

  var text = document.getElementById("announcementid").value;
  var newtext = text.replace(/\n/g, "<br />");
  document.getElementById("announcementid").value = newtext; 

Also, as Konstantin pointed out, the replace() function in Javascript will just replace the first instance unless you pass in a global regular expression.

Fiddle example

Text is a primitive so it would not replace the value. Use a regular expression to globally replace instead of replacing just the first instance:

var text = document.getElementById("announcementid").value;
var newtext = text.replace(/\n/g, "<br />");
document.getElementById("announcementid").value = newtext;

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