Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replacement but only for the substring within quotes [closed]

I have a situation where the given string is

hello,"sai,sur",ya,teja

and the expected output from the given string is

hello,sai-sur,ya,teja

Comma between quotation has to be replace with - character and the rest of the string should be as it is.

like image 972
SaiSurya Avatar asked Oct 21 '20 06:10

SaiSurya


1 Answers

You could get the string within quotes using "([^"]+)" (Regex demo). This will get the string without the quotes to a capturing group. Then, replace all the , with - in the matched string.

The second parameter to replace is function, The first parameter of this replacer function is the entire matched substring, including the quotes. The second parameter is the capturing group. Since you want to to remove the " from the output, you can directly use the capturing group parameter.

const input = `hello,"sai,sur",ya,teja`,
      output = input.replace(/"([^"]+)"/g, (_, g) => g.replace(',', '-'))

console.log(output)
like image 124
adiga Avatar answered Sep 17 '22 18:09

adiga