【问题标题】:How can I transform a string of comma and brackets seperated list into another string?如何将一串逗号和括号分隔的列表转换为另一个字符串?
【发布时间】:2017-11-23 14:19:34
【问题描述】:

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

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);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

我真正需要的结果是:

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

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

【问题讨论】:

  • 您可以使用match 函数从每个字符串match(/[a-zA-Z]+/) 中提取所需的部分作为字母和匹配(/\d+/)作为数字部分

标签: jquery arrays join split


【解决方案1】:

我不是正则表达式专家,但这段代码似乎可以工作,使用 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);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

基于评论的替代方案

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);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

用正则表达式替换

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);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 谢谢。我的问题是,我的名字有时包含数字,而数字包含字母。所以我需要的是获取括号内的值和括号前的值
  • 还有另一个(甚至更好;))解决方案,带有一个有效的正则表达式。
【解决方案2】:

我为你写了你需要的代码,没有 jQuery。

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多