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?
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 ? '' : '"')
You can just do this:
var str = '"" """" """ """""';
var re = /([^"]|^)"("")*(?!")/g;
console.log(str.replace(re, '$1(quotes)')); // '"" """" (quotes) (quotes)'
What that does is the following:
(quotes)
.Basically, it just replaces any odd amount of double-quotes with (quotes)
.
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With