Reputation: 32716
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
Upvotes: 2
Views: 2581
Reputation: 1475
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.
Upvotes: 0
Reputation: 138007
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:
/"([^"]|"")*"/g
/"([^"\\]|\\.)*"/g
Upvotes: 2
Reputation: 785058
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, ','));
"Hello, Tim"
Land of the free, and home of the brave
Upvotes: 1