在所有输入和文本字段中粘贴时,所有空白均已删除,文本为纯文本

时间:2018-09-19 09:35:45

标签: jquery jquery-selectors addeventlistener plaintext clipboarddata

我在这里已经看到了一些这样的问题,我似乎无法使它正常工作。

基本上,我希望复制和粘贴事件仅是纯文本,并删除复制和粘贴过程中除换行符和文本空间以外的所有空白。

(空格表示使用Enter键或空格键无法完成的任何操作,例如Tab键等)

我需要发生这种情况,因为此部分将进入json,如果不这样做,它将破坏json字符串。

我将对报价等进行其他检查。

You can see a jfiddle here

这是我使用的代码:

jQuery(document).ready(function($){

"use strict";

document.querySelector("input, textarea").addEventListener("paste", function(e) {
    e.preventDefault();
    var text = e.clipboardData.getData("text/plain");
    text = text.replace(/^\s+|\s+$/g,'');
    document.execCommand("insertHTML", false, text);
});

});

在此先感谢您提供的帮助。

2 个答案:

答案 0 :(得分:2)

$(document).on('paste', 'textarea', function(e) {
  e.preventDefault();
  var text = e.originalEvent.clipboardData.getData('Text');
  text = text.trim();
  text = text.replace(/\s+/g,' ').trim();
  $(this).val(text);
});

@Robert您可以使用.trim()函数,该函数只能删除开始和结尾空格。 您可以将text = text.trim();替换为text = text.replace(/\s+/g,' ').trim();,它也适用于内部文本。 我想就是你想要的。 如果您想要什么,请随意询问。

答案 1 :(得分:0)

尝试关注

$(document).on('paste', 'textarea', function(e) {
  e.preventDefault();
  var PlainText = e.originalEvent.clipboardData.getData('Text');
  PlainText = PlainText.replace(/\s+/g, '');
  $(this).val(PlainText);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea placeholder="Paste Your Text..."></textarea >