2

I'm looking in a string such as:

"Hello, Tim"

Land of the free, and home of the brave

And I need it to become:

"Hello, Tim"

Land of the free, and home of the brave

This I thought was simple, but for the life of me I can't figure it out. Im importing a corrupt CSV with 1000s of entries via AJAX, so I just need to convert commas INSIDE of double quotes.

How would I go about do this with JavaScript? I can't figure it out. I tried

Oscar Godson
  • 31,662
  • 41
  • 121
  • 201

4 Answers4

3
var str = '"Hello, Tim"\n\
\n\
Land of the free, and home of the brave';

str
.split('"')
.map(function(v,i){ return i%2===0 ? v : v.replace(',',','); })
.join('"');

Check MDC for an implementation of map() for non-supporting browsers.

davin
  • 44,863
  • 9
  • 78
  • 78
2

It is probably easier with a callback function to replace:

s = s.replace(/"[^"]*"/g, function(g0){return g0.replace(/,/g,',');});

At the first step we find all quotes, and replace just the commas in them.

You can even allow escaping quotes:

  • CSV style (with two double quotes) - /"([^"]|"")*"/g
  • String literal style - /"([^"\\]|\\.)*"/g
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • This still doesn't take into account escaped quotes between string, we can complicate it further when needed. – Kobi Jun 13 '11 at 19:45
  • I think I'm also having issues with double quotes in the double quotes PLUS double quotes for HTML. For example: `""Example""`. It's breaking and returning ` – Oscar Godson Jun 13 '11 at 20:05
  • @Oscar - There is no way of guessing from the question that this is what you're doing... The problem is a lot more complex than it appears. Can you please *update the question* with the full details, including a problematic snippet from the JSON/CSV string, with explanation of how a standard parser fails? (Oh, I see you've done that in the comments. Great!) – Kobi Jun 13 '11 at 20:07
  • I think it'd be totally changing the scope of the question. Ill open a new question with more details and everything thats failing... – Oscar Godson Jun 13 '11 at 20:08
1

With the above string as variable html you can use following code:

var m = html.match(/"[\s\S]*"/);
html = html.replace(m[0], m[0].replace(/,/g, ','));

OUTPUT

"Hello, Tim"

Land of the free, and home of the brave
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

result = subject.replace(/("[^"]+?),([^"]*?")/img, "$1,$2");

This will work properly with your example, the only catch is it will not work if you have multiple , inside of the ". If you need it to work with multiple , inside of the " then take a look at this for a more complete way to parse CSV data with javascript.

Community
  • 1
  • 1
daalbert
  • 1,465
  • 9
  • 7