0

In the below string,

'This "is, "just, for", Test", ignore it. My name is "FirstName, LastName".'

I want to replace all Commas(,) only inside the double quotes("") with ###.

For now I only found the matching pattern for (""), but need to build the regex to replace the commas.

/".*?"/g

Could you please help me? Thanks in advance ;)

Expected o/p:

This "is### "just### for"### Test", ignore it. My name is "FirstName### LastName".

Note: This is not dupe of "Find comma in quotes with regex and replace with HTML equiv". Please see my expected o/p(Even I wanna replace the Comma in inner double quotes).

Community
  • 1
  • 1
anupama a
  • 31
  • 5

1 Answers1

1

Grab the string between quotes ", and supply a replacement function as second argument of String.replace to replace all , inside the quotes to ###:

inputString.replace(/"([^"\\]|\\.)*"/g, function ($0) {
    return $0.replace(/,/g, "###");
});

You can paste this code in your console for testing:

'This "is, \\"just, for\\", Test", ignore it. My name is "FirstName, LastName".'.replace(/"([^"\\]|\\.)*"/g, function ($0) {
    return $0.replace(/,/g, "###");
});
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • Thanks :) But its not replacing "," after the "just". – anupama a Oct 17 '14 at 05:56
  • @anupamaa: I don't understand what you mean by inside double quote. The `,` after just is outside, since the previous `"` is already paired up. – nhahtdh Oct 17 '14 at 06:44
  • "just, for" is inner double quotes string. e.g., " "" " – anupama a Oct 17 '14 at 06:47
  • @anupamaa: It's not possible to know that! There is no way to tell those 2 are inner double quotes without escaping. – nhahtdh Oct 17 '14 at 06:52
  • As you said I escaped the inner double quotes, now my string is 'This "is, \"just, for\", Test", ignore it. My name is "FirstName, LastName".'. But still it doesn't replacing the inner quotes Comma, Could you please help me? – anupama a Oct 17 '14 at 17:59
  • @anupamaa: Are you sure it is a single ``\`` or double ``\\``? Single ``\`` in string literal will be lost. Anyway, I will tweak my answer based on the ``\\`` assumption. – nhahtdh Oct 17 '14 at 18:11
  • Yes, this is single "\" only. – anupama a Oct 17 '14 at 18:16