Find comma in quotes with regex and replace with HTML equiv

放肆的年华 提交于 2020-01-10 05:32:06

问题


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


回答1:


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.




回答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



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/6335264/find-comma-in-quotes-with-regex-and-replace-with-html-equiv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!