![]() ![]() Should be sufficient for all the reasonable cases. If you trust the text, why not just use innerHTML? domElement.innerHTML = trustedText.replace(/\r/g, '').replace(/\n/g, '') "How to insert untrusted text into a DOM element?" I'd like to offer a different solution, which tries to tackle the real question that should've been asked here: Nelek's answer is the best one posted so far, but it relies on setting the css value: white-space: pre, which might be undesirable. See here for more details on this method: w3Schools-fromCharCode() H1.innerHTML += "And so on." + omCharCode(13) H1.innerHTML += "Ant the other line here." + omCharCode(13) See my code below: h1.innerHTML += ".I would like to insert a carriage return here." + omCharCode(13) When I tried to use the method it would not preserve the carriage returns, however, using the fromCharCode method it does retain the returns. I needed to be able to cut the text from the text area and save it into notepad. In my case, I needed to generate a CSV file from a long string and write it to a text area. JavaScript has a handy feature called omCharCode() which generates the string version of an ASCII code, or multiple codes separate by a comma. I found a good solution was to use the ASCII representation of carriage returns (CODE 13). I wouldn't resort to creating multiple block elements just to have the text on different lines. Is there a simple way to solve my problem? Here the would do the job, but doing so would replace not just the text content but all the HTML content of my h1, which is not quite what I want. On the other hand, I could change the h1.innerHTML instead of the textContent and write: h1.innerHTML = ".I would like to insert a carriage return here." It doesn't work, probably because the browser considers the '\n' to be pure text and displays it as such (the \r doesn't work either). The problem is, if i write h1.textContent = ".I would like to insert a carriage return here. So this text will display in a new line" Moreover, I would like to insert another carriage return HERE. H1.textContent = "This is a very long string and I would like to insert a carriage return HERE. The string is so long I would like to split it into three chunks: var h1 = document.createElement("h1") Let's say I want to dynamically create a new DOM element and fill up its textContent/innerText ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |