2014-11-22 112 views
2

我有這樣分裂逗號在字符串中使用JavaScript

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

我使用的JavaScript .split()一個字符串,但它返回這樣

n 
m 
klj 
klp 
ml 
io 

但我需要它作爲下面,沒有得到任何想法

n 
m 
klj,klp 
ml 
io 
+0

莫非不可能沒有一個黑客..! :p – 2014-11-22 11:15:39

+0

if(string.indexOf(',')> -1)很好嗎? – aniltc 2014-11-22 11:19:25

+2

jQuery沒有拆分功能嗎?我假設你的意思是標準的JavaScript字符串'.split()'函數。 – nnnnnn 2014-11-22 11:30:31

回答

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文件,你必須尋找更多的陷阱。

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"] 

注意,功能不保留字符串的順序。

0

如果有人想因爲我已經做了沒有硬編碼值,還有另一種方式則只有上述比賽....地圖功能的工作

添加此櫃面你從選擇框闖民宅,文本框等...

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

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