问题描述
||
我正在寻找一个字符串,例如:
\"Hello,Tim\"
Land of the free,and home of the brave
我需要它成为:
\"Hello, Tim\"
Land of the free,and home of the brave
我以为这很简单,但对于我的一生,我无法弄清楚。我通过AJAX导入了包含数千个条目的损坏的CSV,因此我只需要在双引号内转换逗号。
我将如何使用JavaScript做到这一点?我不知道。我试过了
解决方法
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(\'\"\');
对于不支持的浏览器,请检查MDC以获取ѭ3的实现。
, 使用replace
的回调函数可能会更容易:
s = s.replace(/\"[^\"]*\"/g,function(g0){return g0.replace(/,/g,\',\');});
第一步,我们找到所有引号,并仅替换其中的逗号。
您甚至可以允许转义引号:
CSV样式(带有两个双引号)-/\"([^\"]|\"\")*\"/g
字符串文字风格-/\"([^\"\\\\]|\\\\.)*\"/g
, 将上面的字符串作为变量html
可以使用以下代码:
var m = html.match(/\"[\\s\\S]*\"/);
html = html.replace(m[0],m[0].replace(/,\',\'));
输出值
\"Hello, Tim\"
Land of the free,and home of the brave
, result = subject.replace(/(\"[^\"]+?),([^\"]*?\")/img,\"$1,$2\");
这将与您的示例正常运行,唯一的问题是,如果在\"
中有多个ѭ12it,它将不起作用。如果您需要它与\"
中的多个,
配合使用,请查看此内容,以获取更完整的方法来使用javascript解析CSV数据。