开发者

Find comma in quotes with regex and replace with HTML equiv

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


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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜