For string:
'29 July, 2014, 30 July, 2014, 31 July, 2014'
How can I split on every second comma in the string? So that my results are:
[0] => 29 July, 2014
[1] => 30 July, 2014
[2] => 31 July, 2014
Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.
To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.
To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ .
Or this:
var text='29 July, 2014, 30 July, 2014, 31 July, 2014';
result=text.match(/([0-9]+ [A-z]+, [0-9]+)/g);
UPD: You can use this regExp to a find all matches:
// result=text.match(/[^,]+,[^,]+/g);
var text='string1, string2, string3, string4, string5, string 6';
result=text.match(/[^,]+,[^,]+/g);
/*
result:
string1, string2
string3, string4
string5, string 6
*/
You can split with a regular expression. For example:
var s = '29 July, 2014, 30 July, 2014, 31 July, 2014';
s.split(/,(?= \d{2} )/)
returns
["29 July, 2014", " 30 July, 2014", " 31 July, 2014"]
This works OK if all your dates have 2 digits for the day part; ie 1st July will be printed as 01 July.
The reg exp is using a lookahead, so it is saying "split on a comma, if the next four characters are [space][digit][digit][space]".
Edit - I've just improved this by allowing for one or two digits, so this next version will deal with 1 July 2014 as well as 01 July 2014:
s.split(/,(?= \d{1,2} )/)
Edit - I noticed neither my nor SlyBeaver's efforts deal with whitespace; the 2nd and 3rd dates both have leading whitespace. Here's a split solution that trims whitespace:
s.split(/, (?=\d{1,2} )/)
by shifting the problematic space into the delimiter, which is discarded.
["29 July, 2014", "30 July, 2014", "31 July, 2014"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With