View Full Version : Javascript Split troubles =(

08-11-2008, 04:49 PM
Hi, I am having a little difficulty with split. I run into a problem when there are two delimeters in a row

Here is my ugly regular expression
contents = strContents.split(/\".\"|\"\n\"|\"\n\n\"/g)

one of the things it is looking for is "," (quotes included) but when two are in a row ",""," it doesn't give me an empty string for between them

basically the data is set up like this
"something","something else","another thing","","yet another thing"

I want the split to return an array with
0 - "something"
1 - "something else"
2 - "another thing"
3 - ""
4 - "yet another thing"

But it doesn't give me the empty string =( (index 3) and if something is not entered somewhere and there is an empty string it will get skipped and mess up my whole javascript program which is dumping stuff into a DB which won't be good if it messes up...


p.s. I am using IE because the program is not cross browser compatible

08-11-2008, 05:29 PM
why not do something simpler like this

// map is not present in IE
Array.prototype.map = function(cb) {
var ar = [];
for ( i = 0; i < this.length; i++ ) {
ar.push(cb.call(null, this[i], i, this));
return ar;
var t = '"something","something else","another thing","","yet another thing"';
var a = t.split(/,/);
a = a.map(function(v) { return v.replace(/^"|"$/g, ''); });

08-11-2008, 05:53 PM
ummm... ok but I am a little lost =/ It is a little above my head. The whole map thing lost me. Does this take care of the new lines like in the split I wrote with the regular expression? If not how do I put those in there? The data I read from I was trying to split on

edit: I think I see what you are doing now.. you are splitting on the comma and then removing all the quotes. That could work! could I make the expression /,|\n|\n\n/

08-11-2008, 06:12 PM
oh wait, now I know why I can't split on comma.
"Statement Date","June 20, 2008"

Some of the info has a comma inside the quotes =(

contents = strContents.split(/\",|\n+/)

I just searched for a comma that is right after a quote and it did the trick for me with the way you showed me. Thanks

08-11-2008, 07:52 PM
var x = '"something","something else","another thing","","yet another thing"';

function getAllMatches(regexp, text)
res = [];

text = RegExp.rightContext;
return res;
alert(getAllMatches(/^"(.*?)",?/m, x));dumpfi

Too late :/

08-11-2008, 08:57 PM
There's a way to do this, that isn't exactly the most concise way, but it should work pretty well for the purpose and it can be done for pretty much any case you want to do multiple matches (Only exception I can think of is if your pattern allows zero length matches.):
re=/"((?:[^\\"]*(?:\\.)?)+)"/g, // The global flag is necessary for this usage.
input='"something","something else","another thing","","yet another thing","\\""',
re.lastIndex=0; // Reset the lastIndex, this is necessary if you want to reuse the regex.