Skip to content

Commit

Permalink
Fixed embarrassing failure in CSV encoding.
Browse files Browse the repository at this point in the history
  • Loading branch information
mnmldave committed Nov 22, 2010
1 parent 16f32b7 commit d21b2d7
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/js/bit155/csv.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ bit155.csv.cell = function(cell) {
str = cell.toString();
}

if (str.match(/[\\,"\n\r]/)) {
if (str.match(/[,"\n\r]/)) {
str = str.replace(/(\n|\r|\n\r)/g,' ');
str = str.replace(/([\\"])/g, '\\$1');
str = str.replace(/(["])/g, '"$1');
str = '"' + str + '"';
}
return str;
Expand Down
14 changes: 9 additions & 5 deletions src/test/spec/bit155/csv.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,21 @@ describe('csv', function() {
expect(bit155.csv.cell('my, string')).toEqual('"my, string"');
});
it('should escape quotes', function() {
expect(bit155.csv.cell('my "string"')).toEqual('"my \\"string\\""');
expect(bit155.csv.cell('my "string"')).toEqual('"my ""string"""');
});
it('should escape backspace', function() {
expect(bit155.csv.cell('my\\string')).toEqual('"my\\\\string"');
it('should not escape backspace', function() {
expect(bit155.csv.cell('my\\string')).toEqual('my\\string');
});
it('should escape lots', function() {
expect(bit155.csv.cell('my\n"string" is, awesome\\wicked')).toEqual('"my \\"string\\" is, awesome\\\\wicked"');
expect(bit155.csv.cell('my\n"string" is, awesome\\wicked')).toEqual('"my ""string"" is, awesome\\wicked"');
});
it('should not trim', function() {
expect(bit155.csv.cell(' boo, ')).toEqual('" boo, "');
});
it('should escape multiple quotes', function() {
expect(bit155.csv.cell('2.5" / 230,000 px')).toEqual('"2.5"" / 230,000 px"');
});

});

// row
Expand Down Expand Up @@ -101,7 +105,7 @@ describe('csv', function() {
expect(bit155.csv.csv([ ['one','two,too,to'] ])).toEqual('one,"two,too,to"\n');
});
it('should encode a 2d array two rows', function() {
expect(bit155.csv.csv([ ['one','two'], [3, 'four or "for"'] ])).toEqual('one,two\n3,"four or \\\"for\\\""\n');
expect(bit155.csv.csv([ ['one','two'], [3, 'four or "for"'] ])).toEqual('one,two\n3,"four or ""for"""\n');
});
});
});

0 comments on commit d21b2d7

Please sign in to comment.