javascriptregexsanitization

Replace or Strip a specific character between two characters in javascript using regex


replace a specific character between two characters in javascript using regex

My specific requirement is

i want to replace single quote between double quotes.

Ex: sdadads'sdasdads"this is the 'quote" --> sdadads'sdasdads"this is the quote"

i tried

`sdadads'sdasdads"this is the 'quote"`.replace(/\"[^\']\"/g, 'replaced')

but the output is

sdadads'sdasdadsreplaced


Solution

  • You may use this .replace with a function:

    var str = `"this 'is 'the 'quote"`
    
    var repl = str.replace(/"[^"]*"/g, function($0) { 
               return $0.replace(/'/g, ""); });
    
    console.log(repl);
    //=> "this is the quote"