Mena Mena - 18 days ago 6
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''def"

  • "abc''de'f"
    -->
    "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
"abc''de'f"
example, it will "eat" the
f
when replacing the next single quote with two consecutive single quotes, ending up in:

"abc''de''gh"
(see it's missing the
f
!)

Questions


  • 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

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 "''"

Comments