Skip to content
Advertisement

Regex – Replace quote in quotes

The following regex pattern finds the a single double quote in the following string examples (basically the double quote after the 1). The problem is that the positive lookbehind is not supported in some browsers. Is there an alternative regex pattern that would work? I need to replace this double quote with another character using js (eg with a ? character).

(?<=(w|”))”+(?![s])

abc-1″-def321

“abc-1″-def321”

“aloha”

Desired results (replace double quote with a ? character):

abc-1?-def321

“abc-1?-def321”

“aloha”

Thanks.

Advertisement

Answer

I suggest

.replace(/([w"])"+(?=S)/g, '$1?')

See the regex demo. Details:

  • ([w"])Capturing group 1: a word or " char
  • "+ – one or more " chars
  • (?=S) – followed with a non-whitespace char.

See the JavaScript demo:

const text = `abc-1"-def321
"abc-1"-def321"
"aloha"`;
console.log(text.replace(/([w"])"+(?=S)/g, '$1?'));
Advertisement