0

According to this: C# String splitting - breaking string up at second comma

How can I do the same in javascript?

4 Answers 4

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

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

Or more pretty:

var index = mystring.indexOf(',',mystring.indexOf(',')+1);
var substring = mystring.slice(0,index);
Sign up to request clarification or add additional context in comments.

Comments

1

Use this...

var str="test1, 1, anotherstring, 5, yetanother, 400"; 
var n=str.match("([^,]*,[^,]*)(?:, |$)");
console.log(n);

Comments

1

You could also do it without regular expressions:

var splitAtSecondComma = function (str) {
    var arr2 = str.split(",");
    var arr1 = arr2.splice(0,2);
    return [arr1.join(","), arr2.join(",")];
};

Comments

1

Try this one

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.