简体   繁体   中英

Multiline textarea value: line feed not present in all lines

I found a weird bug (?) with textareas...

Say, there's a <textarea> with multiline text (user-pasted text or pre-set text doesn't matter, tested with both).

I want to get the text from <textarea> and replace \\n with something else... Turns out, the .replace works only in the first line.

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. Here's a jsfiddle https://jsfiddle.net/aapgejvb/

Weird huh? Have I just discovered a bug in WebKit or am I stupid?

PS. Tested with jQuery's .val() too, same result (obviously)

PPS. Found this , doesn't help much

.replace("\\n", "<br>") will only replace first occurence of \\n (newline). To replace all you should use replace(/\\n/g, "<br />");

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

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