MarkMark
MarkMark

Reputation: 184

Replace " " to ' ' if there no ' ' inside already

I have a string with different words like

let str = `'code' AND js AND "test" OR "'unit'" AND "work" AND "'apple'" `;

If between " and ", is a '' leave it as it is (like "'unit'" and "'apple'").

If it's simple "word" - replace to 'word' (like "test" and "work")

So output for my string should be:

replacedStr = ` 'code' AND js AND 'test' OR "'unit'" AND 'work' AND "'apple'" `;

I've tried to make it by .replace(/"/g, "'") but it works for all double-ticks.

I think it needed to be done by RegEx but I'm new to it. Maybe someone can help me with it. Would be really grateful!

Upvotes: 0

Views: 56

Answers (1)

JvdV
JvdV

Reputation: 75870

I'm probably overthinking this by a mile, but if there are always pairs of double quotes maybe you could try:

(?=(?:"[^"]*?"[^"]*)+$)"([^"']*?)"

And replace by '$1'. See the online demo.

The idea here is to assert positions that are always followed by pairs of double quotes.

  • (?= - Open positive lookahead:
    • (?: - Open non-capture group:
      • "[^"]*?"[^"]* - Match a double quote, 0+ (lazy) characters other than double quote up to the next double quote. Followed by 0+ characters other than double quote.
      • )+$) - Close non-capture group and match 1+ times up to end string anchor to assure there are always pair(s) of double quotes ahead. Close lookahead.
  • " - An opening double quote.
  • ([^"']*?) - A capture group to grab everything between the two double quotes.
  • " - A closing double quote.

Upvotes: 1

Related Questions