Find comma in quotes with regex and replace with HTML equiv

前端 未结 4 1468
终归单人心
终归单人心 2020-12-21 16:38

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&         


        
相关标签:
4条回答
  • 2020-12-21 17:01

    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 讨论(0)
  • 2020-12-21 17:05

    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
    
    0 讨论(0)
  • 2020-12-21 17:12
    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.

    0 讨论(0)
  • 2020-12-21 17:18

    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
    0 讨论(0)
提交回复
热议问题