Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split on every second comma in javascript

Tags:

javascript

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
like image 704
pjmil Avatar asked Jul 24 '14 09:07

pjmil


People also ask

How to split commas in JavaScript?

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.

How to split by space JavaScript?

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.

How to split string by comma and space?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ .


2 Answers

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
*/
like image 190
SlyBeaver Avatar answered Oct 13 '22 20:10

SlyBeaver


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"]
like image 3
sifriday Avatar answered Oct 13 '22 18:10

sifriday