0

Problem:

I want to format incoming text via paste, but the approach I am taking only allows to replace existing text, or add to it, thus selected text is intacted.

So how to get selected text on paste event.

I don't care for cross browser support.


How should it look like:

  • text inside textarea: aa 12 56 99<-selected text
  • text in clipboard:56abccda6
  • text output:aa 15 6a bc cda6

JavaScript/jquery

$(document).ready(function(){
    function isHex(h) {
        let a = parseInt(h,16);
        return (a.toString(16) ===h.toLowerCase())
    }
    function formatText(text) {
        if(isHex(text)){
            let splitedText = text.match(/[\s\S]{1,2}/g) || [];
            splitedText = splitedText.join(' ');
            return splitedText;
        }
        return text;
    }
    $('textarea[name=plainText]').on('paste', function(event) {
        let formatedText = formatText(event.originalEvent.clipboardData.getData('text'));
        $(this).val($(this).val() + formatedText);
        //or
        //  $(this).val(formatedText);
        return false;
      });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea placeholder="Message" name="plainText" id="plainText" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Message'"></textarea>
Simofy
  • 123
  • 1
  • 6

1 Answers1

0

http://code.google.com/p/rangyinputs

$(document).ready(function(){
        $('textarea[name=plainText]').on('paste', function(event) {
            let formatedText = 
        formatText(event.originalEvent.clipboardData.getData('text'));
        $("#plainText").replaceSelectedText(formatedText);
            return false;
        })
});
Simofy
  • 123
  • 1
  • 6