How to delete the line where the cursor is located in a textarea?

To delete the line where the cursor is located in the textarea, you can follow these steps:

  1. Retrieve the text content from a textarea.
  2. Get the position of the cursor.
  3. Use regular expressions to delete the content of the current line where the cursor is located.
  4. Reset the updated text content back into the textarea.

Below is a sample code demonstrating how to achieve this functionality.

<!DOCTYPE html>
<html>

<body>
  <textarea id="myTextarea" rows="4" cols="50"></textarea>
  <button onclick="deleteCurrentLine()">删除当前行</button>

  <script>
    function deleteCurrentLine() {
      // 获取textarea元素
      var textarea = document.getElementById("myTextarea");

      // 获取文本内容
      var content = textarea.value;

      // 获取光标的位置(起始和结束位置)
      var startPos = textarea.selectionStart;
      var endPos = textarea.selectionEnd;

      // 根据光标位置找到光标所在行的起始和结束位置
      var startLinePos = content.lastIndexOf("\n", startPos - 1) + 1;
      var endLinePos = content.indexOf("\n", endPos);

      // 删除光标所在行的内容
      var updatedContent = content.slice(0, startLinePos) + content.slice(endLinePos);

      // 更新textarea中的文本内容
      textarea.value = updatedContent;
    }
  </script>
</body>

</html>

In the example above, we first get the textarea element and its text content. Then, we use the selectionStart and selectionEnd properties to get the starting and ending positions of the cursor. Next, we use the lastIndexOf and indexOf methods to find the starting and ending positions of the line where the cursor is located. Finally, we use the slice method to delete the content of the line where the cursor is, and then we set the updated text content back into the textarea.

Please note that this example can only delete the line where the cursor is located. If the cursor has selected multiple lines of text, only the first line will be deleted. If you want to be able to handle multi-line deletion, modify the code to suit your needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *