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 limit in split doesn't seem to help...
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 limit in split doesn't seem to help...
You can use:
var splits = str.match(/([^|]*)\|(.*)/);
splits.shift();
The regex splits the string into two matching groups (parenthesized), the text preceding the first | and the text after. Then, we shift
the result to get rid of the whole string match (splits[0]
).
Try this:
function splitOnce(input, splitBy) {
var fullSplit = input.split(splitBy);
var retVal = [];
retVal.push( fullSplit.shift() );
retVal.push( fullSplit.join( splitBy ) );
return retVal;
}
var whatever = splitOnce("1|Ceci n'est pas une pipe: | Oui", '|');
This isn't a pretty approach, but works with decent efficiency:
var string = "1|Ceci n'est pas une pipe: | Oui";
var components = string.split('|');
alert([components.shift(), components.join('|')]);
use the javascript regular expression functionality and take the first captured expression.
the RE would probably look like /^([^|]*)\|/
.
actually, you only need /[^|]*/
if you validated that the string is formatted in such a way, due to javascript regex greediness.
You'd want to use String.indexOf('|')
to get the index of the first occurrence of '|'.
var i = s.indexOf('|');
var splits = [s.slice(0,i), s.slice(i+1)];
Just as evil as most of the answers so far:
var splits = str.split('|');
splits.splice(1, splits.length - 1, splits.slice(1).join('|'));
An alternate, short approach, besides the goods ones elsewhere, is to use replace()
's limit to your advantage.
var str = "1|Ceci n'est pas une pipe: | Oui";
str.replace("|", "aUniquePhraseToSaySplitMe").split("aUniquePhraseToSaySplitMe");
As @sreservoir points out in the comments, the unique phrase must be truly unique--it cannot be in the source you're running this split over, or you'll get the string split into more pieces than you want. An unprintable character, as he says, may do if you're running this against user input (i.e., typed in a browser).