0

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

Sandeep Kumar
  • 234
  • 5
  • 14

3 Answers3

2

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"
  • Using a simple regex to match "..." string using negated character class
  • Inside the function we remove all single quotes
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You could capture the double quotes itself and what is in between the double quotes in a capturing group. Then use a replacement function where you replace all the single quotes in the second capturing group with an empty string

(")([^"]+)(")

let str = `sdadads'sdasdads"this is the 'quote"`;
let res = str.replace(/(")([^"]+)(")/g, function(_, g1, g2, g3) {
  return g1 + g2.replace("'", "") + g3;
});
console.log(res);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
1

Variable width negative lookbehind is not permitted in Javascript, so you may use \K operator to find if a ' is between two double quotes or not using this regex,

"[^']*\K'(?=[^']*")

Explanation:

  • " --> Matches a double quote
  • [^']* --> Matches zero or more characters anything except a single quote
  • \K --> Resets whatever matched so far
  • ' --> Matches a literal single quote
  • (?=[^']*") --> Look ahead ensuring there is a double quote after zero or more any characters except a single quote

Live Demo

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36