简体   繁体   English

多行textarea值:所有行中都不存在换行符

[英]Multiline textarea value: line feed not present in all lines

I found a weird bug (?) with textareas... 我发现了一个奇怪的错误(?)与textareas ...

Say, there's a <textarea> with multiline text (user-pasted text or pre-set text doesn't matter, tested with both). 比方说,有一个带有多行文字的<textarea> (用户粘贴的文本或预先设置的文本无关紧要,用两者进行测试)。

I want to get the text from <textarea> and replace \\n with something else... Turns out, the .replace works only in the first line. 我想从<textarea>获取文本并将\\n替换为其他内容...结果, .replace仅在第一行中起作用。

Here's the code, see what I mean: 这是代码,看看我的意思:

<textarea id="txt">line1
line2
line3
line4</textarea>

<script>
var strval = document.getElementById("txt").value.replace("\n", "<br>");
// strval returns this:

// line1<br>line2
// line3
// line4
</script>

I tested this with Chrome and Firefox. 我用Chrome和Firefox测试了这个。 Here's a jsfiddle https://jsfiddle.net/aapgejvb/ 这是一个jsfiddle https://jsfiddle.net/aapgejvb/

Weird huh? 怪啊? Have I just discovered a bug in WebKit or am I stupid? 我刚刚在WebKit中发现了一个错误或者我是愚蠢的吗?

PS. PS。 Tested with jQuery's .val() too, same result (obviously) 用jQuery的.val()测试,结果相同(显然)

PPS. PPS。 Found this , doesn't help much 发现这一点 ,并没有多大帮助

.replace("\\n", "<br>") will only replace first occurence of \\n (newline). .replace("\\n", "<br>")只会替换\\n (换行符)的第一次出现。 To replace all you should use replace(/\\n/g, "<br />"); 要替换所有你应该使用replace(/\\n/g, "<br />");

Demo : https://jsfiddle.net/aapgejvb/2/ 演示: https//jsfiddle.net/aapgejvb/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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