如何使用jQuery在输入中用逗号替换换行符?

mač*_*ček 2 javascript regex clipboard jquery jquery-events

我有一个输入

<input>
Run Code Online (Sandbox Code Playgroud)

当有人将多行文本粘贴到输入中时,我需要用逗号替换换行符(\r\n、 和\r\n)和制表符。大多数情况下,当用户复制一列或一行时,输入将来自 Microsoft Excel 或 Apple Numbers。\t,

我目前正在尝试这个 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);
    });
});
Run Code Online (Sandbox Code Playgroud)

问题

电子表格中的某些单元格中可能有空格,因此/\s+/g会太宽泛。但是,/[\r\n\t]+/g不起作用。事实上,我认为 jQuery 在删除换行符之前甚至无法访问输入的值。

在 jsFiddle 上一起唱歌

我提供了一个带有预期输入和输出的jsfiddle

<!-- 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
-->
Run Code Online (Sandbox Code Playgroud)

art*_*hur 5

您可以将事件重定向到 textarea,然后获取将满足 \n 字符的粘贴值:

$(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);
    });
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里试试:http//jsfiddle.net/dE3At/