从字符串jq

时间:2017-07-10 13:40:44

标签: javascript jquery

var delivery_nums = ($("#delivery_num").val()).split(",");
var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

for (var num =0 ; num < delivery_nums.length ; num++ ) {

   var input = '<div class="delivery-num-input">';
   input += "<input type='text'  pattern='[0-9]+'\
             class='form-control delivery_number_plus'\
             value='delivery_nums[num]'\
             placeholder='ex(1524587....)' required/>\
             <a href='#' class='remove_field btn btn-sm btn-danger'>\
             Remove</a></div>";
   $(wrapper).append(input); //add input box     

}

delivery_nums的值为['9999999','888888','55555555']它不是数组的字符串所以我将它拆分为数组:

 ['9999999'
 '888888'
'55555555']

我想将此[和]和''删除为数组

2 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.map String.prototype.replace和Number()构造函数

var input = "['9999999', '888888', '55555555']";
var result = input.split(',')
   .map(value => Number(value.replace(/\D/g,''))).join(',');
console.log(result)

答案 1 :(得分:1)

如果您只对字符串使用.split(","),它也会保留[,], and '个字符,因此您需要在使用split()之前将其删除:

var x = "['9999999', '888888', '55555555']";
x = x.replace(/[\[\]' ]/g, '');
console.log(x);
var arr = x.split(",");
console.log(arr);

如果您希望将数组值设为Number()parseInt()这样的数字,则数组值将只包含在字符串中的数字:

arr = arr.map(function(el){
  return Number(el);
}); 

或者只是:

arr = arr.map(Number);