Reputation: 4345
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;
Upvotes: 1
Views: 3978
Reputation: 91600
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.
Upvotes: 3
Reputation: 34895
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;
Upvotes: 0