使用javascript在字符串中用逗号分隔

时间:2014-11-22 11:08:24

标签: javascript jquery

我有一个像这样的字符串

var str = "n,m,'klj,klp',ml,io"; // not the quotes arround klj,klp

我使用javascripts .split()但它会像这样返回

n
m
klj
klp
ml
io

但是我需要它,如下所示,没有任何想法

n
m
klj,klp
ml
io

5 个答案:

答案 0 :(得分:2)

丑陋,简单:

"n,m,'klj,klp',ml,io,'test,test,a,b','test',test".
    match( /'[^']+'|[^,]+/g ).
    map( function( x ) { return x.replace( /^'|'$/g, '' ) } );

结果:

["n", "m", "klj,klp", "ml", "io", "test,test,a,b", "test", "test"]

如果此示例来自CSV文件,则必须留意更多陷阱。

答案 1 :(得分:0)

另一个解决方案:

var splitStrings = (function () {
  var regex = /'.*?'/g;

  return function (str) {
    var results = [], matches;
    matches = str.match(regex);
    if (matches) {
      results = matches.map(function (match) {
        return match.substring(1, match.length-1);
      });
    }
    return results.concat(str.replace(regex, '').split(',').filter(function (s) {
      return s !== '';
    }));
  };
})();

它是一个包含在闭包内的函数,用于保持正则表达式的私有性。

console.log(splitStrings("n,m,'klj,klp',ml,io"));
// prints ["klj,klp", "n", "m", "ml", "io"]

来自Zsolt's answer的示例:

console.log(splitStrings("n,m,'klj,klp',ml,io,'test,test,a,b','test',test"));
// prints ["klj,klp", "test,test,a,b", "test", "n", "m", "ml", "io", "test"]

请注意,该函数不保留字符串的顺序。

答案 2 :(得分:0)

如果有人想不像我所做的那样对硬编码值进行硬编码,那么还有另外一种方法,只有匹配....地图功能工作

添加此选项,您将从selectbox,文本框等引用...

var newValue = $(".client option:selected").text();

      if (/,/i.test(newValue)) {
         newValue = "'" + newValue + "'";
     }
newValue.match( /'[^']+'|[^,]+/g ).
    map( function( x ) { return x.replace( /^'|'$/g, '' ) } );

答案 3 :(得分:0)

类似C的解决方案

function em_split(str) {
    var ret = [], p0 = 0, p1 = 0, p2 = 0, pe = 0;
    while ((p1 = str.indexOf(",",pe)) != -1) {
        if ((p2 = str.indexOf("'",pe)) != -1 ) {
            if (p2 < p1) {
                if (p2==pe) {
                    pe = ((p2 = str.indexOf("'",p1)) == -1) ? p1 : p2;
                } else pe = p1;
            } else pe = p1;
        } else { pe = p1; }
        ret.push(str.substr(p0,pe-p0));
        pe = (pe == p2) ? pe+2 : pe+1;
        p0 = pe;
    }
    ret.push(str.substr(p0,str.length));
    return ret;
}

使用示例:

console.log(em_split("n,m,'klj,klp',ml,io"));
console.log(em_split("n,m,'klj,klp,ml,io"));
console.log(em_split("n,m,klj,klp',ml,io"));

将返回:

Array [ "n", "m", "'klj,klp", "ml", "io" ]
Array [ "n", "m", "'klj", "klp", "ml", "io" ]
Array [ "n", "m", "klj", "klp'", "ml", "io" ]

答案 4 :(得分:0)

您可以使用Array.prototype.split()方法regex进行此操作。

var str = "n,m,'klj,klp',nl,'klj,x,y,klp','klj,klp',ml,io";
var splits = str.split(/'([^']+)'|([^,]+)/);
var results = splits.filter(function(v){
    if (v && v!== ",")
        return true;
    return false;
});

document.write("<br>Output: " + JSON.stringify(results));