简体   繁体   中英

How to format text in a html <textarea>?

So I have a <textarea> on my page, and when I click a button, the value of the text in the textarea is assigned to .innerHTML of a paragraph on my page. Now let's say I type something like this in the textarea : Hey how's it going ? The paragraph would look like this Hey how's it going ? . Basically, it wouldn't have <br> tags at the end of each row. Is there any way I can force the JS function to insert <br> tags at the end of each row of my textarea?

Or is there an easier way to do this?

Thanks.

JavaScript code : document.getElementById("sendMsgBtn").onclick=function(){ var element = document.createElement("p"); element.style.borderBottom = "1px solid black"; var content = document.createTextNode(document.getElementById("currentMsg").value); content = content.replace( /\\n/g, "<br>"); element.appendChild(content); document.body.appendChild(element); document.getElementById("currentMsg").value = ""; } document.getElementById("sendMsgBtn").onclick=function(){ var element = document.createElement("p"); element.style.borderBottom = "1px solid black"; var content = document.createTextNode(document.getElementById("currentMsg").value); content = content.replace( /\\n/g, "<br>"); element.appendChild(content); document.body.appendChild(element); document.getElementById("currentMsg").value = ""; }

You don't want line breaks. Trust me.

Just set this:

white-space: pre-wrap;

This CSS will make whitespace significant, preserving it as it was typed.

When you copy the element from the textarea to the paragraph tag, replace all line breaks with <br> tags:

var input = document.getElementById("myTextarea").innerHTML; // get textarea contents
input = input.replace( /\n/g, "<br>"); // replace line breaks with <br> tags
document.getElementById("myParagraph").innerHTML = input; // place html-ified input into your <p>

If you are using jQuery, try this:

function nl2br (str, is_xhtml) {   
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

Then: nl2br(yourVariableWithContent); can be used to change newline characters (the ones that the return button makes) into
.

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