如何将逗号和括号分隔列表的字符串转换为另一个字符串?

时间:2017-11-23 14:19:35

标签: jquery arrays join split

我尝试将我的字符串(即值列表)转换为另一个字符串。 我有问题,因为我真的不知道怎么做。这是我到目前为止所取得的成就:

var input = "cat(13),dog(12),bird(14)";
var array = input.split(',');
   
var result = [];

$(array).each(function( g, h ) {
    result.push("("+h.split(")").join('id:-name:-<br>'));
});

$(document.body).append(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我实际需要的结果是:

id:13-name:cat-
id:12-name:dog-
id:14-name:bird-

但我被卡住了......

2 个答案:

答案 0 :(得分:2)

我不是正则表达式专家,但此代码似乎有效,使用match()函数:

var input = "cat(13),dog(12),bird(14)";
var array = input.split(',');
   
var result = [];

$(array).each(function( g, h ) {
  result.push(
    'id:' +
    h.match(/\d+/) + /* matches the numbers */
    '-name:' +
    h.match(/[a-z]+/i) + /* matches the text */
    '-<br />'
    );
});

$(document.body).append(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

基于评论的备选方案

var input = "c4t(13a),d0gg13(1ab2),bird(14)";
var array = input.split(',');
   
var result = [];

$(array).each(function( g, h ) {
  var split = h.split('(');
  result.push(
    'id:' +
    split[0] + /* matches the numbers */
    '-name:' +
    split[1].slice(0,-1) + /* matches the text */
    '-<br />'
    );
});

$(document.body).append(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

与正则表达式相对应

var input = "c4t(13a),d0gg13(1ab2),bird(14)";
var array = input.split(',');
   
var result = [];

$(array).each(function( g, h ) {
  result.push(h.replace(/(\w+)\((\w+)\)/, 'id:$1-name:$2-<br />'));
});

$(document.body).append(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

我为你编写了没有jQuery所需的代码。

&#13;
&#13;
var input = "cat(13),dog(12),bird(14)";
var array = input.split(',');
   
var result = [];

// other way of looping an array
for(var i=0;i<array.length;i++){
    // this way you replace the entry with another string with inserted parameters;
    // if you need more info on how what works you can ask me or search for "regex" and "js string replace"
    result.push(array[i].replace(/(\w+)\((\d+)\)/,function(full,p1,p2){return "id:"+p2+"-name:"+p1+"-";}));
};
console.log(result);

document.body.innerHTML += result;
&#13;
&#13;
&#13;