Cristian Crishk Cristian Crishk - 10 months ago 147
Javascript Question

How to get the final pasted text in jquery?

I want to trim a text in a field when the user is writing or paste text on it, the following code works great but has only one problem, when the user selects all the text to replace it with the pasted text or put the cursor to insert the pasted text inside, the code repeats the present value + the new value at the end, How can I fix it?

$(document).on('paste', "input[type='text'], textarea", function(e) {

let val = $(this).val();
val = val.trim();
val = val.replace(/(?:^\s+|\s+?(\s))(\S+)/g, "$1$2");
val = val.replace(/\s+(\s)$/, "$1");
$(this).val( val );

} );

I believe what I need to do is to paste normally, get the final pasted text and trim it, but that is the question How to get the final pasted text? Can you help?

Answer Source

In short, the paste event isn't a pipeline that allows you to change the pasting text on the fly. You can access the clipboard, but getting the data from it is a bit challenging as there is questionable browser support not only for the paste event, but for the clipboardData within said event.

onChange or onBlur are your best bets, as this is a great time to update your values even after a user pastes their value:

$("input[type='text'], textarea").bind('blur', function(e) {
} );

This will work, whether they type in the whitespaces, or paste them in. If it has to be pasted, then you may want to instead have the above, and a paste event, but the paste event merely sets a shared boolean like "valueIsPasted" to be true, and then you can do the above only when that value is true. I don't love that solution, but unfortunately, the paste support isn't great. On top of that, that still will not work in IE, which doesn't support the paste event.


Looks like W3Schools begs to differ on browser support; however, I still feel that onChange or onBlur are your best bets as it will allow you to change the value once the user is done editing the value or done with the control, and definitely work. Check out my codepen.