如何在 HTML textarea 中新增換行符?


為了在 HTML textarea 中新增換行符,我們可以使用 HTML 換行標籤 `
` 在需要的地方插入換行。或者,我們也可以使用 CSS 屬性 `"white-space: pre-wrap"` 自動為文字新增換行符。這在 textarea 中顯示預格式化文字時特別有用。因此,讓我們討論一下新增換行符的方法。

方法

  • 在 HTML 中建立一個 textarea 併為其分配一個 id。

  • 建立一個按鈕,單擊該按鈕將使用換行符分割 textarea 的文字。

  • 現在建立將文字換行的函式。此函式的程式碼如下:

function replacePeriodsWithLineBreaks() {
   // Get the textarea element
   var textarea = document.getElementById("textarea");
   
   // Get the text from the textarea
   var text = textarea.value;
   
   // Replace periods with line breaks
   text = text.replace(/\./g, "
"); // Update the textarea with the new text textarea.value = text; }

示例

此方法的最終程式碼將是:

<!DOCTYPE html>
<html>
<head>
   <title>Add Line Breaks</title>
</head>
   <body>
      <textarea id="textarea" rows="10" cols="50"></textarea>
      <br>
      <button id="replace-btn" onclick="replacePeriodsWithLineBreaks()">Replace Periods with Line Breaks</button>
      <script>
         // Function to replace periods with line breaks in the textarea
         function replacePeriodsWithLineBreaks() {
            // Get the textarea element
            var textarea = document.getElementById("textarea");
            
            // Get the text from the textarea
            var text = textarea.value;
            
            // Replace periods with line breaks
            text = text.replace(/\./g, "
"); // Update the textarea with the new text textarea.value = text; } </script> </body> </html>

在這個例子中,JavaScript 程式碼首先使用 `getElementById()` 方法透過其 id 獲取 textarea 元素。然後,它使用 `value` 屬性從 textarea 獲取文字。接下來,它使用 `replace()` 方法替換所有句點例項為換行符。最後,它使用 `value` 屬性更新 textarea 的新文字。

注意:正則表示式 `/\./g` 中的 `g` 標誌用於替換所有出現的句點。如果沒有它,則只會替換第一個出現的句點。

更新於:2023年2月9日

12K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告