Mena Mena - 1 year ago 83
Javascript Question

Replace character if not preceded nor followed by same character

I am trying to replace non-consecutive single quotes in a string with two consecutive quotes.

Examples (in/out)

  • "abc'def"

  • "abc''de'f"

  • etc.

Javascript doesn't support lookbehinds, so the following regular expression I'd use with Java (well, more or less) will not compile:

myString.replace(/(?<!)'(?!'))/g, "''");

I have looked around SO and some answers advise using a non-capturing group containing a custom character class negating the character that would otherwise be in the negative lookbehind:

myString.replace(/(?:[^'])'(?!'))/g, "''");

However, that will not do either: it will successfully not replace the two consecutive single quotes, but in the
example, it will "eat" the
when replacing the next single quote with two consecutive single quotes, ending up in:

(see it's missing the


  • Is there a suitable regex-based solution for this problem?

  • If not, should I just go with a barbaric iteration and indexing of all the input string's characters and painfully build another string from it (please no)?

Answer Source

As multiple (=more than 2) quotes are not an issue for you, you don't actually need to take that much care, if there are one or two quotes at a given place, just - so just replace every occurence of quotes with the wanted double quotes. The regex for this would be /'+/g and can be replaced by "''"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download