【问题标题】:jquery split textarea value by comma and new linejquery用逗号和换行符分割textarea值
【发布时间】:2016-02-15 07:19:37
【问题描述】:

我有这个 texarea,我想在用户键入后用逗号和换行符解析它的值。示例。

输入

 /*  inside textarea */
   2 water, 4 ice
   6 lemon

输出:

  Total # of Items: 3

  Item #               Quantity          Item Name
    1                     2               Water
    2                     4                Ice 
    3                     6               Lemon 

这是目前为止的代码:

$('#$name').keyup(function (event) {
$("#textAreaDiv").show();   
if(event.keyCode == 188){
    $("#textAreaTaggingDetails").html(getItems($('#$name').val().split('\\n'), 'comma'));   
    //console.log("comma press");
}   
else if (event.keyCode == 13) {     
    //console.log("new line press");
    $("#textAreaTaggingDetails").html(getItems($('#$name').val().split(','), 'newLine'));   
}

});

 function getItems(eachLine, type){     
   var xcontent = "";       
   $("#titleTextAreaTagging").html('Total # of Items: ' + eachLine.length + '<br/>');

   for(var i = 0, l = eachLine.length; i < l; i++) {

       var quantity = (eachLine[i]).match(/\d+/);
       var itemName = (eachLine[i]).replace(/[0-9]+/, "");

       xcontent += "<div class=\"col-md-4\"><h6 class=\"text-info mn\" id=\"titleTextAreaTagging\">"+ (i+1) +"</h6></div><div class=\"col-md-4\"><h6 class=\"text-info mn\" id=\"titleTextAreaTagging\">"+ quantity  +"</h6></div><div class=\"col-md-4\"><h6 class=\"text-info mn\" id=\"titleTextAreaTagging\">"+ itemName +"</h6></div>";

  }

  return xcontent;

}

有了这个,我只能用新行得到正确的输出,但不能用逗号

【问题讨论】:

    标签: jquery split


    【解决方案1】:

    你可以做的是,你可以先用逗号替换所有新行,然后用逗号分割,这很容易。

    str = $('#$name').val().replace(/(?:\r\n|\r|\n)/g, ',');
    
    
    var partsOfStr = str.split(',');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多