0

据此:C#字符串拆分 - 在第二个逗号处分解字符串

我怎样才能在javascript中做同样的事情?

4

4 回答 4

2
var mystring = "test1, 1, anotherstring, 5, yetanother, 400";

var subString = mystring.slice(0,mystring.indexOf(',',mystring.indexOf(',')+1));

或者更漂亮:

var index = mystring.indexOf(',',mystring.indexOf(',')+1);
var substring = mystring.slice(0,index);
于 2013-05-28T22:07:03.010 回答
1

用这个...

var str="test1, 1, anotherstring, 5, yetanother, 400"; 
var n=str.match("([^,]*,[^,]*)(?:, |$)");
console.log(n);
于 2013-05-28T21:54:47.557 回答
1

您也可以不使用正则表达式:

var splitAtSecondComma = function (str) {
    var arr2 = str.split(",");
    var arr1 = arr2.splice(0,2);
    return [arr1.join(","), arr2.join(",")];
};
于 2013-05-28T22:01:20.007 回答
1

试试这个

function splitSecondComma(str) {
  var arr = str.split(","),
  l = arr.length,
  arr2 = [];
  for(i= 0; i < l; i= i+2) {
    arr2.push(arr[i] + " " + arr[i+1]);
  }
  return arr2
}
于 2013-05-28T23:40:26.920 回答