Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace newline with comma in input using jQuery?

I have an input

<input>

When someone pastes multi-line text into the input, I need the newlines (\r, \n, and \r\n) and tabs \t replaced with a comma ,. Most of the time, the input will be coming from Microsoft Excel or Apple Numbers when a user copies a column or a row.

I am currently trying this jQuery

$(function(){
    // jQuery paste event. how trendy!
    $('input').on('paste', function(e){
        var e = $(this);
        setTimeout(function(){
            e.val( $.trim(e.val()).replace(/\s+/g, ',') );
        }, 0);
    });
});

The problem

Some cells in their spreadsheet might have spaces in them so /\s+/g is going to be too broad. However, /[\r\n\t]+/g isn't working. In fact, I don't think jQuery even has access to the input's value before the newlines are being removed.

Sing along on jsFiddle

I've provided a jsfiddle with expected inputs and outputs

<!-- sample input, copy below this line --
one
2
hello world
foo bar
m3000
-- end copy -->

<!-- output should look like
one, 2, hello world, foo bar, m3000
-->
like image 895
maček Avatar asked Jan 24 '26 06:01

maček


2 Answers

You can redirect the event to a textarea and then get the paste value which will content the \n characters:

$(function(){
    $('input').on('paste', function(e){
        var target = $(e.target);
        var textArea = $("<textarea></textarea>");
        textArea.bind("blur", function(e) {
            target.val(textArea.val().replace(/\r?\n/g, ', ') );
            textArea.remove();
        });
        $("body").append(textArea);
        textArea.focus();
        setTimeout(function(){
            target.focus();
        }, 10);
    });
});

You can try it here: http://jsfiddle.net/dE3At/

like image 150
arthur Avatar answered Jan 25 '26 21:01

arthur


I am afraid this is not possible (without hacking around).

  • The newlines will be removed when your pasted data is set as the value of the input, so you cannot retrieve the original version by reading the value of the input.
  • You cannot get the pasted data itself in the onpaste event (IE has the proprietary clipboardData.getData(), but there is no not-hacky cross-browser way).

I suggest you use a textarea, so you can maintain those newlines and do whatever you want to them. You can style the textarea to look like an input, disable resizing and make it have only one row.

jsFiddle Demo with textarea

like image 43
kapa Avatar answered Jan 25 '26 22:01

kapa