2

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

6

You can do this using a callback ...

var r = s.replace(/"[^"]+"/g, function(v) { 
      return v.replace(/,/g, '###');
});
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • Wow great :), Could you please explain what exactly first and second replace doing? – anupama a Oct 16 '14 at 23:34
  • 1
    The first replacement matches double quotes and everything in between them `v` (the matched content), the second replacement replaces all commas that are inside of the double quotes. – hwnd Oct 16 '14 at 23:36
  • Thanks for your response. I have a doubt here, to match double quotes we can use "/".*?"/g" also know, Could you please explain why you used negated class[^"], I mean why you are negotiate " inside the double quotes?, Thanks in advance. – anupama a Oct 16 '14 at 23:42
  • The negated class means any character except `"` one or more times. Which I used to reduce backtracking. – hwnd Oct 16 '14 at 23:46
  • Thanks again. But I want to replace all commas those are inside double quotes. e.g, if we get the string like 'This "is, "just, for", Test", ignore it.'. Here I want to replace all Commas except in front of "ignore". Could you please help me out from this? – anupama a Oct 17 '14 at 00:47
  • With the negated double quote combined with `+`, how does the engine know to stop at the second quote? – 1252748 Oct 17 '14 at 01:01
  • Hi, any luck for my question? --- I want to replace all commas those are inside double quotes. e.g, if we get the string like 'This "is, "just, for", Test", ignore it.'. Here I want to replace all Commas except in front of "ignore". Could you please help me out from this? – anupama a Oct 17 '14 at 01:24
  • Yes, don't use regex if that is the case. – hwnd Oct 17 '14 at 01:35