簡體   English   中英

粘貼前替換剪貼板中的特殊字符

[英]Replace special characters from clipboard before pasting

我使用了一個小 js 函數,它允許將剪貼板的內容粘貼到 textarea 中。 見下文。 我粘貼的數據來自excel,並用特殊字符分隔\\r\\n我需要在粘貼之前直接用逗號“,”替換這些特殊字符有沒有簡單的方法? 提前感謝

 function Coller() { navigator.clipboard.readText().then(clipText => document.getElementById("textarea").innerText = clipText); }
 <button onclick="Coller()">Coller</button> <textarea id="textarea" rows="10" cols="40"></textarea>

您可以使用 String.prototype.replace() 函數解決這個問題。 ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace )

你可以這樣使用它:

function Coller() {
    navigator.clipboard.readText().then(clipText =>
    document.getElementById("textarea").innerText = clipText.replace(/["]/gm, '').replace(/[\r\n]+/gm, ','));
}

在這種情況下, \\r (在 Mac 上創建)、 \\n (在 Linux 上創建)和\\r\\n (在 Windows 上創建)將被替換。

  • g代表全局,因此字符串中的每個特殊字符都將被替換
  • m代表多行,所以即使你的文本有幾行,所有的特殊字符也會被替換

用正則表達式替換特殊字符:

document.getElementById("textarea").innerText = clipText.replace(/\r\n/g, ',');

示例:

 let text = "Cherry\\r\\nOrange\\r\\nApple" console.log(text.replace(/\\r\\n/g, ','))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM