1252748
1252748

Reputation: 15372

replace all commas within a quoted string

is there any way to capture and replace all the commas within a string contained within quotation marks and not any commas outside of it. I'd like to change them to pipes, however this:

/("(.*?)?,(.*?)")/gm

is only getting the first instance:

JSBIN

Upvotes: 1

Views: 1942

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39532

If callbacks are okay, you can go for something like this:

var str = '"test, test2, & test3",1324,,,,http://www.asdf.com';

var result = str.replace(/"[^"]+"/g, function (match) {
    return match.replace(/,/g, '|');
});

console.log(result);
//"test| test2| & test3",1324,,,,http://www.asdf.com

Upvotes: 5

user797257
user797257

Reputation:

This is very convoluted compared to regular expression version, however, I wanted to do this if just for the sake of experiment:

var PEG = require("pegjs");

var parser = PEG.buildParser(
    ["start = seq",
     "delimited = d:[^,\"]* { return d; }",
     "quoted = q:[^\"]* { return q; }",
     "quote = q:[\"] { return q; }",
     "comma = c:[,] { return ''; }",
     "dseq = delimited comma dseq / delimited",
     "string = quote dseq quote",
     "seq = quoted string seq / quoted quote? quoted?"].join("\n")
);

function flatten(array) {
    return (array instanceof Array) ?
        [].concat.apply([], array.map(flatten)) :
        array;
}

flatten(parser.parse('foo "bar,bur,ber" baz "bbbr" "blerh')).join("");
// 'foo "barburber" baz "bbbr" "blerh'

I don't advise you to do this in this particular case, but maybe it will create some interest :)

PS. pegjs can be found here: (I'm not an author and have no affiliation, I simply like PEG) http://pegjs.majda.cz/documentation

Upvotes: 0

Related Questions