본문 바로가기
🌔Developers/JavaScript \ HTML

[JS] 입력된 줄바꿈 저장하기

by 키훈마스 2023. 2. 19.
반응형
<textarea id="myTextarea"></textarea>
<button onclick="showText()">Show Text</button>
<div id="myText"></div>

<script>
  function showText() {
    const myTextarea = document.getElementById("myTextarea");
    const myText = document.getElementById("myText");
    const text = myTextarea.value;

    // Replace any occurrences of '\n' with '<br>' to preserve line breaks
    const html = text.replace(/\n/g, '<br>');

    // Set the innerHTML of the myText element to the HTML with preserved line breaks
    myText.innerHTML = html;
  }
</script>
반응형