2014-12-02 105 views
0

我想將每個,,都粘貼到textarea的字符串分割爲新行。另外:替換空白行後應刪除。爲新行分割粘貼文本(textarea)

所以這個:

apple,bananas, tomatoes, ,anything. 

應該得到:

apple 
bananas 
tomatoes 
anything. 

我嘗試:

$("#txtcomplaint").bind('paste', function(e) { 
    var elem = $(this); 
    setTimeout(function() { 
     var text = elem.val(); 
     $("#txtcomplaint").val(text.replace(', ', '\n').replace(',', '\n')); 
    }, 100); 
}); 
+0

究竟什麼是它的問題?你會得到什麼結果? – Avishek 2014-12-02 13:52:48

+0

小提琴鏈接請 – 2014-12-02 13:54:38

+1

爲什麼超時? – 2014-12-02 13:56:54

回答

1

你的代碼的工作,你只需要同時刪除空格周圍的物品和刪除重複的換行符:

$("#txtcomplaint").bind('paste', function(e) { 
    var elem = $(this); 
    setTimeout(function() { 
     elem.val(function(i, val) { 
      return $.trim(val.replace(/\s?,\s?/g, '\n').replace(/\n+/g, '\n')); 
     }); 
    }, 20); 
}); 

Example fiddle

0

試試這個

var str="apple,bananas, tomatoes, ,anything"; 
    var lines = str.split(/,/); 
    var texts = []; 
    for (var i=0; i < lines.length; i++) { 
     if (/\S/.test(lines[i])) { 
     texts.push($.trim(lines[i])); 
     } 
    } 
    var n = texts.toString().split(",").join("\n"); 
    $("#txtcomplaint") .val(n); 

小提琴Demo-- http://jsfiddle.net/RahulB007/2cqxbu7v/