Regex to detect an odd number of consecutive quotes

javascript, regex

Solution

Are the quotes consecutive? Unless I've misunderstood your requirement, this would work...

str = str.replace(/\"\"?/g, '""')

Explanation: Matches a single quote, optionally followed by another quote, and replaces one/both with two quotes.

Example: http://jsfiddle.net/aR6p2/

Or alternatively, if it's just a matter of appending a quote when there's an odd number of quotes in a string...

  var count = str.split('"').length - 1
  str = str + (count % 2 == 0 ? '' : '"')

Problem

If a string contains a single quote `"`, I need to replace it with double quotes `""`. However, sometimes a valid double-quote can be followed by a single quote, eg. `"""`, which just needs another quote added to the end. If I use a standard replace, eg. `replace('"', '""')`, all the quotes are turned into doubles, of course, not just the odd one. What I need is to find any odd number of consecutive quotes (including a single one on its own) and simply add another quote onto the end. Eg. `"` becomes `""`, and `"""` becomes `""""`. Is there a regex replace in JavaScript which can accomplish this?

Original source