[英]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. 我试图使用多行文本框将文本插入到显示为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. 我想用javascript取文本框内的文本并找到用户按下的位置并在该位置放置“
<br/>
”,这样当显示文本时它将显示换行符。 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. newtext
变量最终是来自announcementid
元素的原始字符串的副本 。 Thus, you'll need to re -set the value
property on the original document element: 因此,您需要在原始文档元素上重新设置
value
属性:
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. 此外,正如Konstantin所指出的,除非传入全局正则表达式,否则Javascript中的
replace()
函数将替换第一个实例。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.