Replace odd matches with typographic opening quote, and even matches with typographic closing quote

372 Views Asked by At

I'm trying to replace regular quote symbols ( " ) in a text with typographic quotes (« and »).

Is there a way to replace odd quote matches with « and even matches with » ?

So: Hello "world"! Becomes: Hello «world»!

Also, it shouldn't have any problem if the text doesn't have an even number of quotes, since this is intended to be performed "on the fly"

Thanks for your help!

2

There are 2 best solutions below

0
On BEST ANSWER
/**
 * @param {string} input the string with normal double quotes
 * @return {string} string with the quotes replaced
 */
function quotify(input) {
  var idx = 0;
  var q = ['«', '»'];
  return input.replace(/"/g, function() {
    var ret = q[idx];
    idx = 1 - idx;
    return ret;
  });
}
2
On

I've come up with another way to do this, but I'm not sure which one is more "optimized":

function quotify2(inputStr)
{
    var quotes = inputStr.match(/«|»/g);
    return inputStr.replace(/"/g, (quotes && quotes.length % 2 != 0 ? '»' : '«'));
}