How can I split a string only once, i.e. make 1|Ceci n\'est pas une pipe: | Oui
parse to: [\"1\", \"Ceci n\'est pas une pipe: | Oui\"]
?
The
If the string doesn't contain the delimiter @NickCraver's solution will still return an array of two elements, the second being an empty string. I prefer the behavior to match that of split. That is, if the input string does not contain the delimiter return just an array with a single element.
var splitOnce = function(str, delim) {
var components = str.split(delim);
var result = [components.shift()];
if(components.length) {
result.push(components.join(delim));
}
return result;
};
splitOnce("a b c d", " "); // ["a", "b c d"]
splitOnce("a", " "); // ["a"]